-
sorting ABC order
currently I have this method of sorting with c++ (ABC order)
Code:
#include <algorithm>
#include <string>
#include <ctype.h>
struct sort_pred {
bool operator()(const string &left,const string &right) {
for(string::const_iterator lit=left.begin(), rit=right.begin(); lit != left.end() && rit != right.end(); ++lit,++rit)
if( tolower(*lit) < tolower(*rit))
return true;
else if( tolower( *lit ) > tolower( *rit ) )
return false;
if( left.length() < right.length() )
return true;
return false;
}
};
int main()
{
//some vector<string> vec
sort(vec.begin(),vec.end(),sort_pred());
}
Is there a more simple way to sort words in abc order?
I have heard that in Java there is simply the "compareTo" method that returns positive if first word is closer to A than the second.. (along with a compareTo for doubles and other types as well)
is there a similar method in c++ stl?
-
Yes. Lose the predicate function and then it will work.
-
hmm what if I was sorting a vector of structs which contain a string?
i would still need the predicate function right?
(thats what it really is, but i didnt want to include the struct since it would overcomplicate my question)
Code:
struct player
{
string name;
int id;
}
int main()
{
vector<player> players;
sort(players.begin(), players.end());
//INCORRECT
}
THANKS!!!
-
> hmm what if I was sorting a vector of structs which contain a string?
Then you write a comparison function using the string operators > or <.
> i would still need the predicate function right?
Yes in that case you would.
> (thats what it really is, but i didnt want to include the struct since it would overcomplicate my question)
No it wouldn't over complicate anything. In fact it led to a completely different answer.
-
The fact that you're using tolower at all suggests to me that you're looking for a case-insensitive sort of those strings. If this is the case all you do is: Code:
#include <cctype> // for toupper
#include <string>
#include <algorithm>
using namespace std;
bool operator()(string left, string right) {
transform(left.begin(), left.end(), left.begin(), (int(*)(int)) toupper);
transform(right.begin(), right.end(), right.begin(), (int(*)(int)) toupper);
return left < right;
}
Now if this is a struct then you wont want to modify the contents of those strings when comparing them, so be sure you make a copy first in that case.