c++ - What my customized compare does not work? -


i wrote compare operator 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 , line2 make "2" ahead of "20" when sorting. causes runtime error. error "invalid operator<" on visual studio.

the return value of std::string::compare doesn't have 1 when a "greater than" b. has greater 0.

instead of

return a.compare(b) == 1 ? true : false; 

i think need:

return (a.compare(b) < 0); 

Popular posts from this blog