如何在 c++ 中根据第二个元素按降序对列表进行排序
How to sort a list of pairs based on second element in decreasing order in c++
我想知道是否有办法根据第二个元素对我的对列表进行排序。这是一个代码:
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;
}
相关文章:
- 为什么我的递归函数按降序打印,然后按升序打印?
- 我正在尝试按降序对地图进行排序,但没有得到预期的结果?
- 如何在 c++ 中根据第二个元素按降序对列表进行排序
- 如何按矩阵行的总和降序对矩阵进行排序 C++.
- priority_queue使用降序向量实现最小堆的语法差异
- 插入按降序排序
- 如何使用cpp编写选择排序算法以降序对元素列表进行排序?
- 我怎么不能按课程代码的降序对数字进行排序
- 如何使用布尔函数按降序对数组进行排序?
- 如何按降序排序?
- 程序,它接受用户输入的字符并按出现的降序显示它们
- 数组将排序排序为降序而不是升序
- 如何按降序对标准数组进行排序 - C++ 11.
- 如何按降序打印数组?
- 按降序C 排序矢量
- 使用相同的 for 循环按升序或降序遍历地图
- 使用QuickSort算法以降序排序向量
- 按降序对双链接列表进行排序
- 按字母顺序降序对列表进行排序,然后打印列表
- 查找升序列表中降序的第一个和最后一个数字