[英]sort function does not work properly (c++)
I am trying to sort a vector<pair<string, int>> list
, however the sorting seems to not work properly for me.我正在尝试对
vector<pair<string, int>> list
进行排序,但是排序对我来说似乎无法正常工作。
The vector of pairs contains person's name for a string and years for an integer.对的向量包含字符串的人名和 integer 的年份。
The task is to sort the list by years and if they are same sort by name alphabetically.任务是按年份对列表进行排序,如果它们相同,则按名称按字母顺序排序。
The input:输入:
John 20
Tom 25
Mark 20
The output should be : output 应该是:
John 20
Mark 20
Tom 25
My program does not change anything and I cannot find what is wrong.我的程序没有改变任何东西,我找不到问题所在。 I would appreciate some help.
我会很感激一些帮助。
My code:我的代码:
vector<pair<string, int>> list;
list.push_back({ "John", 20 });
list.push_back({ "Tom", 25 });
list.push_back({ "Mark", 20 });
sort(list.begin(), list.end(), [](pair<string, int>& a, pair<string, int>& b)
{
if (a.second < b.second)
return a.second > b.second;
return a.first < b.first;
}
);
for (const auto& x : list)
cout << x.first << " " << x.second << endl;
You need your comparison functor to return true
if a.second < b.second
is true
but如果
a.second < b.second
为true
,则您需要比较函子返回true
,但
if (a.second < b.second) // if this is `true`
return a.second > b.second; // this will always be `false`
A simple approach to correct it is to make a top-down filter like this:纠正它的一种简单方法是制作一个自上而下的过滤器,如下所示:
sort(list.begin(), list.end(), [](const auto& a, const b& rhs){
if(a.second < b.second) return true;
if(b.second < a.second) return false; // note: the operands are flipped
// if reaching here, a.second and b.second are considered equal (which is
// not the same as `==` in cases where the operands are floating points)
return a.first < b.first; // compare the remaining member
});
The above can be made simpler by using std::tie
:使用
std::tie
可以使上述内容变得更简单:
sort(list.begin(), list.end(), [](const auto& a, const auto& b){
return std::tie(a.second, a.first) < std::tie(b.second, b.first);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.