简体   繁体   English

用c ++对一对矢量进行排序

[英]sort a pair vector in c++

#include "bits/stdc++.h"
using namespace std;
int main()
{
int i,j;
vector< pair<int,int> > v;

    v.push_back(make_pair(4,2));
    v.push_back(make_pair(1,3));
    v.push_back(make_pair(5,4));

sort(v.begin(), v.end());

for(i=0;i<v.size();i++)
    cout<<v[i].first<<" "<<v[i].second<<endl;
}

The output to the above code is--- 上面代码的输出是---

1 3 
4 2
5 4

We can see from the output that sort function has sorted v[i].first but what if we only want to sort v[i].second or if we want to sort both of them,how to then accomplish the task? 我们可以从输出中看到sort函数已经对v [i] .first进行了排序,但是如果我们只想对v [i] .second进行排序,或者如果我们想要对它们进行排序,那么如何完成任务呢?

Specify your custom comparer. 指定自定义比较器。 In C++14 it can be done very concisely: 在C ++ 14中,它可以非常简洁地完成:

sort(v.begin(), v.end(), [](const auto& x, const auto& y){return x.second < y.second;});

The std::sort() function accepts a comparison function object as a parameter: std::sort()函数接受比较函数对象作为参数:

template<class RandomIt, class Compare> void sort(
    RandomIt first, RandomIt last, Compare comp);

A working comparison function for the second member of pair would be: second成员pair工作比较函数是:

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

By default it would sort on the basis of first element much as your program is doing. 默认情况下,它会根据您的程序正在进行的第一个元素排序。 However you could pass third argument to sort as your-defined comparator to do what-ever you want to do... 但是你可以传递第三个参数来排序为你定义的比较器来做你想做的事......

You can have your own comparator for sorting on right element:- 您可以使用自己的比较器对右侧元素进行排序: -

struct sort_second {
    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_second());

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM