我如何根据第一或第二个对更大的值对成对排序
How do I sort array of pairs based on the greater value in first or second
bool custome_compare(const pair<int, int>& p1, const pair<int, int>& p2){
if (p1.first > p1.second || p1.second > p1.first) return true;
else return false;
}
int main()
{
pair<int, int> arr[4];
arr[0].first = 4, arr[0].second = 10;
arr[1].first = 7, arr[1].second = 6;
arr[2].first = 3, arr[2].second = 8;
arr[3].first = 9, arr[3].second = 1;
sort(arr, arr + 4 , custome_compare);
//---------------------------------------
return 0;
}
我的目标是根据更大的值对成对阵列进行排序。
我不在乎更大的价值是这对的第一个或第二个元素。
例如,我有这对:
4,10
7,6
3,8
9,1
对它们进行排序:
4,10
9,1
3,8
7,6
所以我不是基于第一个或第二个基于两个基于两者进行排序的排序。
如何编辑此比较函数以完成此任务?
预先感谢。
您是
bool custome_compare(const std::pair<int, int> &p1, const std::pair<int, int> &p2)
{
return std::max( p1.first, p1.second ) > std::max( p2.first, p2.second );
}
这是一个指示的程序
#include <iostream>
#include <utility>
#include <algorithm>
#include <iterator>
bool custome_compare(const std::pair<int, int> &p1, const std::pair<int, int> &p2)
{
return std::max( p1.first, p1.second ) > std::max( p2.first, p2.second );
}
int main()
{
std::pair<int, int> arr[] =
{
{ 4, 10 }, { 7, 6 }, { 3, 8 }, { 9, 1 }
};
for ( const auto &p : arr )
{
std::cout << p.first << ", " << p.second << 'n';
}
std::cout << std::endl;
std::sort( std::begin( arr ), std::end( arr ), custome_compare );
for ( const auto &p : arr )
{
std::cout << p.first << ", " << p.second << 'n';
}
std::cout << std::endl;
return 0;
}
其输出是
4, 10
7, 6
3, 8
9, 1
4, 10
9, 1
3, 8
7, 6
听起来您想比较两对的最大值。
bool custom_compare(const pair<int, int>& p1, const pair<int, int>& p2){
return std::max(p1.first, p1.second) < std::max(p2.first, p2.second);
}
自定义比较函数应比较对(s)的最大值。所以类似:
bool custom_compare(pair<int, int> i, pair<int, int> j) { return max(i.first,
i.second) > max(j.first, j.second); }
未经测试,也没有尝试编译,但我希望您可以从这里解决问题。
相关文章:
- 如何在 c++ 中根据第二个元素按降序对列表进行排序
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 如何根据对的第二个元素对 STL c++ 中的一组对进行排序?
- C++ - 同时对向量的第一个和第二个进行排序
- 为什么我的代码没有对数组中第二个索引上的数据进行排序?
- 按第一个值的递减顺序对一组对进行排序,然后按第二个值的字母顺序排序
- 如何仅根据第二个元素对map<int,pair<int,int> >进行排序?
- 我如何根据第一或第二个对更大的值对成对排序
- 使用 pair 创建priority_queue,以便在第一个元素相等时"<"第一个元素的排序,对第二个元素">"排序
- 在 c++ 中给出两个整数向量(大小和类型相同),我想从最小到最大元素对一个进行排序,并更改第二个向量的顺序
- 如何按第一个,然后是第二个,然后是第三个对 2d 数组进行排序,..使用 C++ 的列
- 如何根据第一个元素对增加然后根据第二个元素减少对进行排序
- 如何按第一个 STL 列表的顺序对第二个 STL 列表进行排序
- 如何保持按第二个元素排序的对的优先级队列?
- 使用c++中的第二个索引数组对数组进行排序
- 如何基于第二个字符串对字符串向量的向量排序
- 对第二个元素没有比较器的pair进行排序
- 按第一个值和第二个值将输入排序到一个链表中
- STXXL:如何对第二个元素上的向量对排序
- 如何对一对向量按降序排序,并按第二个元素排序