How can I build a std::vector and then sort them?

前端 未结 7 2056
一向
一向 2021-02-06 22:09

I have a bunch of strings that I need to sort. I think a std::vector would be the easiest way to do this. However, I\'ve never used vectors before and so would like some help.

7条回答
  •  梦如初夏
    2021-02-06 22:42

    You can just do

    std::sort(data.begin(), data.end());
    

    And it will sort your strings. Then go through them checking whether they are in order

    if(names.empty())
        return true; // empty vector sorted correctly
    for(std::vector::iterator i=names.begin(), j=i+1; 
            j != names.end(); 
            ++i, ++j)
        if(*i > *j)
            return false;
    return true; // sort verified
    

    In particular, std::string::compare couldn't be used as a comparator, because it doesn't do what sort wants it to do: Return true if the first argument is less than the second, and return false otherwise. If you use sort like above, it will just use operator<, which will do exactly that (i.e std::string makes it return first.compare(second) < 0).

提交回复
热议问题