Reputation: 193
I wrote a compare operator as below:
struct GreaterThan
{
bool operator() (string a, string b)
{
if (a.length() == 1 && a[0] == b[0]) //LINE1
{
return true;
}
if (b.length() == 1 && b[0] == a[0]) //LINE2
{
return true;
}
return a.compare(b) == 1 ? true : false;
}
};
vector<string> v{"2", "20", "5", "7"};
sort(v.begin(), v.end(), GreaterThan());
The purpose of LINE1 and LINE2 is to make "2" ahead of "20" when sorting. But it causes runtime error. The error is "invalid operator<" on visual studio.
Upvotes: 0
Views: 54
Reputation: 206567
The return value of std::string::compare
doesn't have to be 1
when a
is "greater than" b
. It just has to be greater than 0
.
Instead of
return a.compare(b) == 1 ? true : false;
I think you need:
return (a.compare(b) < 0);
Upvotes: 1