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); });
Niall source share