如何对向量<对<字符串、对<int、int>>>进行排序?
How to sort a vector<pair<string , pair<int , int>>>?
我希望能够对以下向量进行排序-向量<对<字符串,对<int,int>>基于对的第一个元素<int,int>,如果它们相等,那么根据它们的第二个元素对它们进行排序,我如何在C++中使用STL的构造来做到这一点?
这种类型必须在的线路上完成一些事情
假设E1和E2是两个元素
如果第一个E1秒==第一个E2秒,则必须对第二个元素进行比较。
如果你不能使用C++11功能,你仍然可以做这样的事情:
typedef std::pair<std::string, std::pair<int, int>> AnkitSablok;
struct my_compare {
bool operator()(const AnkitSablok &lhs, const AnkitSablok &rhs) const {
return lhs.second < rhs.second;
}
};
int main()
{
std::vector<AnkitSablok> vec;
std::sort(vec.begin(), vec.end(), my_compare());
}
[…]基于对<int,int>,如果它们相等,则根据它们的第二个元素对它们进行排序[…]
std::pair
已经有了字典比较C++03 20.2.2/6:
template <class T1, class T2>
bool operator<(const pair<T1, T2>& x, const pair<T1, T2>& y);
Returns: x.first < y.first || (!(y.first < x.first) && x.second < y.second)
所以,正如WhozCraig所指出的,你应该只比较外对的.second
s。
这是一个lambda表达式,我没有C++11,没有其他可能的方法吗?
使用函数:
struct LessSecond
{
template<typename T, typename U>
bool operator()(const std::pair<T,U> &x, const std::pair<T,U> &y) const
{
return x.second < y.second;
}
};
// ...
sort(x.begin(), x.end(), LessSecond());
或者更通用的版本(取决于您的需求):
struct LessSecondGeneric
{
template<typename Pair>
bool operator()(const Pair &x, const Pair &y) const
{
return x.second < y.second;
}
};
现场演示:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <utility>
#include <vector>
struct LessSecond
{
template<typename T, typename U>
bool operator()(const std::pair<T,U> &x, const std::pair<T,U> &y) const
{
return x.second < y.second;
}
};
int main()
{
using namespace std;
vector<pair<string , pair<int, int>>> x
{
{"1", {2, 1}}, {"2", {1, 1}}, {"3", {1, 2}}
};
sort(x.begin(), x.end(), LessSecond());
for(const auto &p : x)
cout << p.first << " (" << p.second.first << ", " << p.second.second << ")" << endl;
}
输出为:
2 (1, 1)
3 (1, 2)
1 (2, 1)
sort(x.begin, x.end, [](const X & a, const X & b){return a.second.first < b.second.first ; }) ;
其中x是容器,x是元素的类型。
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- EASTL矢量<向量<int>>连续的
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 什么是模板&lt;&gt;inline bla bla
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- eigen :: llt&lt;eigen :: matrixxd&gt;具有不完整的类型
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是std :: set&lt; std :: future&gt;不可能存在
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- opencv 2.4.7在iOS错误背景_segm.hpp #include&lt; list&gt;未找到
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- ///<评论></评论>在Visual Studio中