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.
I just need to sort them alphanumerically, nothing special. Indeed, the string::compare function would work.
After that, how can I iterate through them to verify that they’re sorted?
Here’s what I have so far:
std::sort(data.begin(), data.end(), std::string::compare); for(std::vector<std::string>::iterator i = data.begin(); i != data.end(); ++i) { printf('%s\n', i.c_str); }
You can just do
And it will sort your strings. Then go through them checking whether they are in order
In particular,
std::string::comparecouldn’t be used as a comparator, because it doesn’t do whatsortwants it to do: Return true if the first argument is less than the second, and return false otherwise. If you usesortlike above, it will just useoperator<, which will do exactly that (i.estd::stringmakes it returnfirst.compare(second) < 0).