[英]Why isn't my overloading < operator not working for STL sort
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;
As noted, your operator<
is not being called, std::string
already has overloaded operators in the std
namespace. 如前所述,没有调用您的operator<
, std::string
在std
名称空间中已经有重载的运算符。
There are two versions of std::sort
, one that will use operator<
and another that takes a custom predicate to sort the container. std::sort
有两种版本,一种将使用operator<
,另一种将使用自定义谓词对容器进行排序。 Add a custom predicate, you can still used sort
to sort your vector
as required; 添加一个自定义谓词,您仍然可以根据需要使用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;
}
I've called it lastchar
, but you can name it what ever is best. 我称它为lastchar
,但您可以将其命名为最好的。 As an added bonus, if you can used C++11 or above, you can make the predicate a lambda. 另外,如果您可以使用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);
});
It's not being used, you have to pass it into std::sort
- something like: 它没有被使用,您必须将其传递到std::sort
类似:
sort(nameList.begin(), nameList.end(), [](const string &s1, const string &s2) {
return s1.at(s1.size() - 1) < s2.at(s2.size() - 1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.