我有以下代码,我想根据字符串的最后一个字符排序字符串向量。 我已完成以下操作,但排序是通过默认规则完成的。
这是重载<部分:
bool operator<(const string &s1, const string &s2){ return s1.at(s1.size() - 1) < s2.at(s2.size() - 1); }这主要是:
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;代码中的代码: LINK
I have this following code where I want to sort vector of string according to the last character of the string. I've done the following but the sorting is done by default rules.
Here's the overloading < part:
bool operator<(const string &s1, const string &s2){ return s1.at(s1.size() - 1) < s2.at(s2.size() - 1); }This is in 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()); for(int i = 0; i < nameList.size(); i++) cout<<nameList.at(i)<<endl;Code in ideone: LINK
最满意答案
如上所述,您的operator<未被调用, std::string已经在std命名空间中重载了运算符。
有两个版本的std::sort ,一个使用operator< ,另一个使用自定义谓词对容器进行排序。 添加自定义谓词,您仍然可以根据需要使用sort对vector进行排序;
#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; }我把它叫做lastchar ,但你可以把它命名为最好的。 作为额外的好处,如果你可以使用C ++ 11或更高版本,你可以使谓词成为lambda。
sort(nameList.begin(), nameList.end(), [] (const string &s1, const string &s2){ return s1.at(s1.size() - 1) < s2.at(s2.size() - 1); });As noted, your operator< is not being called, std::string already has overloaded operators in the std namespace.
There are two versions of std::sort, one that will use operator< and another that takes a custom predicate to sort the container. Add a custom predicate, you can still used sort to sort your vector as required;
#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've called it lastchar, but you can name it what ever is best. As an added bonus, if you can used C++11 or above, 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); });更多推荐
发布评论