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
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<std::string>::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).
What is the question exactly? It seems everything is already there.
However, you should probably use std::cout << *i << std::endl;
i is an iterator == pointer to the data in the container, so * is neededc_str() is a function of std::string and not a variableThe problems in your code do not relate to your question?
Some hints for you:
std::vector also overrides [] operator, so you can instead save the iterator hassle and use it like an array (iterate from 0 to vector.size()).std::set instead, which has automatically sorting on insertion (binary tree), so you save the extra sorting.copy(V.begin(), V.end(), ostream_iterator<std::string>(cout, "\n")); If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With