简体   繁体   English

如何根据对的第二个元素对对的向量进行排序?

[英]How do I sort a vector of pairs based on the second element of the pair?

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?是否有简便的方法来进行排序在基于对的第二元素递增的顺序列表?

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?我知道我可以编写一个小函数对象来完成这项工作,但是有没有办法使用STLstd::less现有部分直接完成这项工作?

EDIT: 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 : using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type auto .编辑:使用 c++14,最好的解决方案很容易编写,这要归功于现在可以具有auto类型参数的 lambdas。 This is my current favorite solution这是我目前最喜欢的解决方案

std::sort(v.begin(), v.end(), [](auto &left, auto &right) {
    return left.second < right.second;
});

ORIGINAL ANSWER :原始答案

Just use a custom comparator (it's an optional 3rd argument to std::sort )只需使用自定义比较器(它是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());

If you're using a C++11 compiler, you can write the same using lambdas:如果您使用的是 C++11 编译器,则可以使用 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);
    }
};

then you can do this too:那么你也可以这样做:

std::sort(v.begin(), v.end(), sort_pair_second<int, int>());

or even甚至

std::sort(v.begin(), v.end(), sort_pair_second<int, int, std::greater<int> >());

Though to be honest, this is all a bit overkill, just write the 3 line function and be done with it :-P虽然说实话,这有点矫枉过正,只需编写 3 行函数并完成它:-P

You can use boost like this:您可以像这样使用提升:

std::sort(a.begin(), a.end(), 
          boost::bind(&std::pair<int, int>::second, _1) <
          boost::bind(&std::pair<int, int>::second, _2));

I don't know a standard way to do this equally short and concise, but you can grab boost::bind it's all consisting of headers.我不知道一个标准的方法来做到这一点同样简短,但你可以抓住boost::bind它都是由标题组成的。

Its pretty simple you use the sort function from algorithm and add your own compare function它非常简单,您可以使用算法中的排序功能并添加您自己的比较功能

vector< pair<int,int > > v;
sort(v.begin(),v.end(),myComparison);

Now you have to make the comparison based on the second selection so declare you "myComparison" as现在您必须根据第二个选择进行比较,因此将“myComparison”声明为

bool myComparison(const pair<int,int> &a,const pair<int,int> &b)
{
       return a.second<b.second;
}

With C++0x we can use lambda functions:使用 C++0x,我们可以使用 lambda 函数:

using namespace std;
vector<pair<int, int>> v;
        .
        .
sort(v.begin(), v.end(),
     [](const pair<int, int>& lhs, const pair<int, int>& rhs) {
             return lhs.second < rhs.second; } );

In this example the return type bool is implicitly deduced.在此示例中,返回类型bool是隐式推导的。

Lambda return types Lambda 返回类型

When a lambda-function has a single statement, and this is a return-statement, the compiler can deduce the return type.当 lambda 函数只有一条语句并且这是一个返回语句时,编译器可以推断返回类型。 From C++11, §5.1.2/4:从 C++11,§5.1.2/4:

... ...

  • If the compound-statement is of the form { return expression ; }如果复合语句的形式为{ return expression ; } { return expression ; } the type of the returned expression after lvalue-to-rvalue conversion (4.1), array-to-pointer conversion (4.2), and function-to-pointer conversion (4.3); { return expression ; }返回的表达的左值到右值转换(4.1),阵列到指针转换(4.2),和功能到指针转换(4.3)后的类型;
  • otherwise, void .否则, void

To explicitly specify the return type use the form []() -> Type { } , like in:要显式指定返回类型,请使用[]() -> Type { } ,例如:

sort(v.begin(), v.end(),
     [](const pair<int, int>& lhs, const pair<int, int>& rhs) -> bool {
             if (lhs.second == 0)
                 return true;
             return lhs.second < rhs.second; } );

For something reusable:对于可重用的东西:

template<template <typename> class P = std::less >
struct compare_pair_second {
    template<class T1, class T2> bool operator()(const std::pair<T1, T2>& left, const std::pair<T1, T2>& right) {
        return P<T2>()(left.second, right.second);
    }
};

You can use it as您可以将其用作

std::sort(foo.begin(), foo.end(), compare_pair_second<>());

or或者

std::sort(foo.begin(), foo.end(), compare_pair_second<std::less>());

您必须依赖非标准的select2nd

尝试交换对的元素,以便您可以正常使用std::sort()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据成对中的第一个和第二个元素对成对向量进行排序? - How do I sort a vector of pairs based on both first and second element in a pair? STXXL:如何对第二个元素上的对向量进行排序? - STXXL: How to sort Vector of pairs on second element? 如何按降序和第二个元素对对向量排序? - How to sort a vector of pairs in descending order and by the second element? 如何按两个值而不是第二个值对成对向量进行排序? - How do I sort a vector of pairs by both of the values rather than just the second one? 根据对的第二个值查找对向量的上限 - Finding the upper bound of vector of pairs based on second value of pair 如何基于第一或第二个较大的值对对数组进行排序 - How do I sort array of pairs based on the greater value in first or second 如何根据对的第二个元素对 STL c++ 中的对集进行排序? - How to sort set of pairs in STL c++ according to second element of pair? 创建一个对的向量,其中一对的第二个元素指向向量中的下一个对 - Create a vector of pairs, where the second element of a pair points to the next pair in the vector 如何通过第一个元素对向量进行排序? - How to sort a vector of pairs by first element? 排序函数如何作用于一对整数对的向量? - How sort function works on vector of pair of pairs of integer?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM