[英]How do I sort a vector of pairs based on both first and second element in a pair?
如果我有一个成对的vector<pair<int, int>> arr;
并传递元素,如
4 5
3 7
10 5
5 7
1 5
我怎样才能让这对元素以降序排列取决于一对中的第一个和第二个元素
5 7
3 7
10 5
4 5
1 5
或按升序
1 5
4 5
10 5
3 7
5 7
编辑:我想要对向量进行排序取决于双方,例如第二个元素5与第一个元素 (4, 10, 1) 重复 3 次,第二个元素7与第一个元素 (3, 5) 重复 2 次
所以如果我按降序对它们进行排序,重复的7将首先出现,然后是5,它会是这样的
3 7
5 7
4 5
10 5
1 5
然后用7也按降序对第一个元素进行排序成为 (5, 3) 然后用5 的第一个元素成为 (10, 4, 1) 所以最终的数组将是这样的
5 7
3 7
10 5
4 5
1 5
使用std::sort ,并应用适当的排序标准:
#include <algorithm>
#include <vector>
#include <utility>
#include <iostream>
bool SortAscending(const std::pair<int,int>& p1, const std::pair<int,int>& p2)
{
return std::tie(p1.second, p1.first) < std::tie(p2.second, p2.first);
}
bool SortDescending(const std::pair<int,int>& p1, const std::pair<int,int>& p2)
{
return std::tie(p1.second, p1.first) > std::tie(p2.second, p2.first);
}
int main()
{
std::vector<std::pair<int, int>> arr =
{{4, 5},{3, 7}, {10, 5}, {5, 7},{1, 5}};
std::cout << "Original: \n";
for (auto& p : arr)
std::cout << p.first << " " << p.second << "\n";
std::sort(arr.begin(), arr.end(), SortAscending);
std::cout << "\n\nAscending: \n";
for (auto& p : arr)
std::cout << p.first << " " << p.second << "\n";
std::sort(arr.begin(), arr.end(), SortDescending);
std::cout << "\n\nDescending: \n";
for (auto& p : arr)
std::cout << p.first << " " << p.second << "\n";
}
输出:
Original:
4 5
3 7
10 5
5 7
1 5
Ascending:
1 5
4 5
10 5
3 7
5 7
Descending:
5 7
3 7
10 5
4 5
1 5
您可以简单地使用 std::sort 按升序对其进行排序
std::vector<std::pair<int, int>> arr;
arr.push_back({ 4, 5 });
arr.push_back({ 3, 7 });
arr.push_back({ 10, 5 });
arr.push_back({ 5, 7 });
arr.push_back({ 1, 5 });
std::sort(arr.begin(), arr.end());
此外,您可以使用 std::greater<>() 按降序排序
std::sort(arr.begin(), arr.end(), std::greater<>());
编辑后:如果您的问题是按第二个元素排序,而不是第二个元素等于按第一个元素排序,那么这可能是一个解决方案
(按升序排列)
bool sortBySecondElement(const std::pair<int, int>& p1, const std::pair<int, int> & p2)
{
return p1.second < p2.second;
}
bool sortByFirstElement(const std::pair<int, int>& p1, const std::pair<int, int>& p2)
{
return p1.second == p2.second && p1.first < p2.first;
}
int main()
{
std::vector<std::pair<int, int>> arr;
arr.push_back({ 4, 5 });
arr.push_back({ 3, 7 });
arr.push_back({ 10, 5 });
arr.push_back({ 5, 7 });
arr.push_back({ 1, 5 });
std::sort(arr.begin(), arr.end(), sortBySecondElement);
std::sort(arr.begin(), arr.end(), sortByFirstElement);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.