如何在 c++ 中根据第二个元素按降序对列表进行排序

How to sort a list of pairs based on second element in decreasing order in c++

本文关键字:降序 列表 排序 元素 第二个 c++      更新时间:2023-10-16

我想知道是否有办法根据第二个元素对我的对列表进行排序。这是一个代码:

std::list<std::pair<std::string, unsigned int>> words;
words.push_back(std::make_pair("aba", 23);
words.push_back(std::make_pair("ab", 20);
words.push_back(std::make_pair("aBa", 15);
words.push_back(std::make_pair("acC", 8);
words.push_back(std::make_pair("aaa", 23);

我想按降序对基于整数元素的列表词进行排序,以便我的列表如下所示:

<"aba", 23>,<"aaa", 23>,<"ab", 20>,<"aBa", 15>,<"acC", 8>

另外,是否可以按第一个和第二个元素对它们进行排序,以便它首先按第二个元素(按整数值(排序,然后如果有两个或多个具有相同第二个元素的对(即相同的整数值(,那么它将根据第一个元素按字母顺序对这些元素进行排序, 那么我上面排序列表中的前 2 对将交换,因此:

<"aaa", 23>,<"aba", 23>,<"ab", 20>,<"aBa", 15>,<"acC", 8>
我想根据

整数元素按降序对我的列表词进行排序

排序谓词必须返回true如果传递的第一个元素(即第一对(在建立的顺序中第二个元素之前

传递:
words.sort([](auto const& a, auto const& b) {
return a.second > b.second;
});

由于你想按降序对列表进行排序,如果它的第二个元素(即int(大于b的第二个元素,则a对将排在b之前。


请注意,std::sort()不适用于对std::list进行排序,因为它需要随机访问迭代器,但std::list仅提供双向迭代器

是否可以按第一个和第二个元素对它们进行排序,以便它首先按第二个元素(按整数值

(排序,然后如果有两个或多个具有相同第二个元素的对(即相同的整数值(,那么它将根据第一个元素按字母顺序对这些元素进行排序

再次假设int元素的顺序递减,当两个元素相同时,只需求助于对的第二个元素int

lst.sort([](auto const& a, auto const& b) {
if (a.second > b.second)
return true;
if (a.second < b.second)
return false;
return a.first < b.first;
});

或更简洁,感谢std::tie()

lst.sort([](auto const& a, auto const& b) {
return std::tie(b.second, a.first) < std::tie(a.second, a.first);
});

>std::list有一个成员函数std::list::sort应该进行排序。

它的两个重载之一接受自定义比较功能:

template <class Compare>
void sort(Compare comp);

您可以按如下方式使用:

words.sort([](const std::pair<string, unsigned int> &x,
const std::pair<string, unsigned int> &y)
{
return x.second > y.second;
});

我们正在 bool 中创建一个比较函数,该函数比较两对的第二个值,并首先给出返回的更大值,然后使用该函数简单地完成排序。

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

bool compare(const pair<int,int>& a, const pair<int,int>& b){
return a.second > b.second;
}
int main() {
vector<pair<int,int>> v = {{1, 5}, {2, 3}, {3, 8}, {4, 2}, {5, 1}};

// sorting the vector of pairs by second value
sort(v.begin(), v.end(), compare);

// printing the sorted vector of pairs
for(auto x: v){
cout << x.first << " " << x.second << endl;
}

return 0;
}