如果我有一个成对的向量:
If I have a vector of pairs:
std::vector<std::pair<int, int> > vec;
是否有一种简单的方法可以根据对的第二个元素以递增顺序对列表进行排序?
Is there and easy way to sort the list in increasing order based on the second element of the pair?
我知道我可以编写一个小函数对象来完成这项工作,但是有没有办法使用 STL 和 std::less
的现有部分来直接做工作?
I know I can write a little function object that will do the work, but is there a way to use existing parts of the STL and std::less
to do the work directly?
我知道我可以编写一个单独的函数或类来传递给要排序的第三个参数.问题是我是否可以用标准的东西来构建它.我真的很喜欢这样的东西:
I understand that I can write a separate function or class to pass to the third argument to sort. The question is whether or not I can build it out of standard stuff. I'd really something that looks like:
std::sort(vec.begin(), vec.end(), std::something_magic<int, int, std::less>());
EDIT:使用 c++14,最好的解决方案很容易编写,这要归功于 lambdas 现在可以具有类型参数<代码>自动代码>.这是我目前最喜欢的解决方案
EDIT: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type auto
. This is my current favorite solution
std::sort(v.begin(), v.end(), [](auto &left, auto &right) {
return left.second < right.second;
});
原始答案:
只需使用自定义比较器(它是 std::sort
的可选第三个参数)
Just use a custom comparator (it's an optional 3rd argument to std::sort
)
struct sort_pred {
bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
}
};
std::sort(v.begin(), v.end(), sort_pred());
如果您使用的是 C++11 编译器,则可以使用 lambdas 编写相同的代码:
If you're using a C++11 compiler, you can write the same using lambdas:
std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
});
编辑:为了回应您对问题的编辑,这里有一些想法......如果您真的想要有创意并且能够大量重复使用这个概念,只需制作一个模板:
EDIT: in response to your edits to your question, here's some thoughts ... if you really wanna be creative and be able to reuse this concept a lot, just make a template:
template <class T1, class T2, class Pred = std::less<T2> >
struct sort_pair_second {
bool operator()(const std::pair<T1,T2>&left, const std::pair<T1,T2>&right) {
Pred p;
return p(left.second, right.second);
}
};
那么你也可以这样做:
std::sort(v.begin(), v.end(), sort_pair_second<int, int>());
甚至
std::sort(v.begin(), v.end(), sort_pair_second<int, int, std::greater<int> >());
虽然说实话,这有点矫枉过正,只写3行函数就可以了:-P
Though to be honest, this is all a bit overkill, just write the 3 line function and be done with it :-P
这篇关于如何根据对的第二个元素对对的向量进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!