【发布时间】:2013-11-22 21:56:43
【问题描述】:
我希望能够对以下向量进行排序 - vector> > 基于 pair 的第一个元素,如果它们相等,则根据它们的第二个元素对它们进行排序,我如何使用 STL 在 C++ 中做到这一点构造?
这个排序必须完成一些事情
假设 E1 和 E2 是 2 个元素
如果 E1.second.first == E2.second.first 则必须针对第二个元素进行比较。
【问题讨论】:
我希望能够对以下向量进行排序 - vector> > 基于 pair 的第一个元素,如果它们相等,则根据它们的第二个元素对它们进行排序,我如何使用 STL 在 C++ 中做到这一点构造?
这个排序必须完成一些事情
假设 E1 和 E2 是 2 个元素
如果 E1.second.first == E2.second.first 则必须针对第二个元素进行比较。
【问题讨论】:
如果您不能使用 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());
}
【讨论】:
(),为什么不超载operator<。不需要仿函数,排序看起来更整洁std::sort(vec.begin(), vec.end());
std::sort 采用可选的比较函数。这需要是一个可调用对象,例如函数指针、函数对象或 lambda。我只针对您的问题发布了一种可能的解决方案。
[...] 基于对 的第一个元素,如果它们相等,则根据它们的第二个元素对它们进行排序[...]
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 指出的那样,您应该只比较外对的 .seconds。
这是一个 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 是元素的类型。
【讨论】: