Why does my overload not work <statement does not work for STL sorting

I have the following code where I want to sort a string vector according to the last character of a string. I did the following, but sorting is done by default.

Here overload <part:

 bool operator<(const string &s1, const string &s2){ return s1.at(s1.size() - 1) < s2.at(s2.size() - 1); } 

This is basically:

 vector <string> nameList; int n; cin>>n; while(n--){ string name; char str[100]; cin>>str; name += str; nameList.push_back(name); } sort(nameList.begin(), nameList.end()); for(int i = 0; i < nameList.size(); i++) cout<<nameList.at(i)<<endl; 

Code in ideon: LINK

0
source share
2 answers

As already noted, your operator< not called, std::string has already overloaded the operators in the std .

There are two versions of std::sort , one of which will use operator< , and the other for a custom predicate to sort the container. Add a custom predicate, you can still use sort to sort the vector as needed;

 #include <algorithm> #include <string> #include <iostream> #include <vector> using namespace std; bool lastchar(const string &s1, const string &s2){ return s1.at(s1.size() - 1) < s2.at(s2.size() - 1); } int main(){ vector <string> nameList; int n; cin>>n; while(n--){ string name; char str[100]; cin>>str; name += str; nameList.push_back(name); } sort(nameList.begin(), nameList.end(), &lastchar); for(int i = 0; i < nameList.size(); i++) cout<<endl<<nameList.at(i); return 0; } 

I called it lastchar , but you can call it the best. As an added bonus, if you can use C ++ 11 or higher, you can make the predicate a lambda.

 sort(nameList.begin(), nameList.end(), [] (const string &s1, const string &s2){ return s1.at(s1.size() - 1) < s2.at(s2.size() - 1); }); 
+6
source

It is not used, you should pass it to std::sort - something like:

 sort(nameList.begin(), nameList.end(), [](const string &s1, const string &s2) { return s1.at(s1.size() - 1) < s2.at(s2.size() - 1); } 
+3
source

Source: https://habr.com/ru/post/1203208/


All Articles