is there a way to sort a vector of strings alphabeticly ? or do i got to make my own function to do it. and one more is there a way to compare a string with all of the strings in a vector... (is it done the same way as a array??)
thanks
This is a discussion on STL vectors within the C++ Programming forums, part of the General Programming Boards category; is there a way to sort a vector of strings alphabeticly ? or do i got to make my own ...
is there a way to sort a vector of strings alphabeticly ? or do i got to make my own function to do it. and one more is there a way to compare a string with all of the strings in a vector... (is it done the same way as a array??)
thanks
i answered the first part of my question sort( , ) i thought it could only do int but i was wrong.
std::sort and std::find.
Code:vector<string> vec; vec.push_back("BBB"); vec.push_back("CCC"); vec.push_back("AAA"); cout << "Before:"; copy(vec.begin(), vec.end(), ostream_iterator<string>(cout, " ")); std::sort(vec.begin(), vec.end()); cout << endl << "After:"; copy(vec.begin(), vec.end(), ostream_iterator<string>(cout, " "));
By default, the sort STL function will use the less-than (<) operator defined for whatever type is stored in the vector. This means any type that has a less-than operator defined for it can be pushed onto a vector and sorted using sort. Since the string container has a less-than operator defined for it that works alphabetically, calling the sort function will sort the elements in the vector in an alphabetic fashion. This also means that you can come up with a user defined type (class or struct), define the less-than operator for it, push a bunch of these objects into a vector, and then call sort and the vector will end up sorted according to the rules of your less-than operator.
I used to be an adventurer like you... then I took an arrow to the knee.
std::binary_search is more efficient than std::find if your vector is already sorted.
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law