如何对矢量<pair <string,=“”pair <int =“”,=“”int =“”>&gt;&gt;?</pair <string>进行排序

时间:2013-11-22 21:56:43

标签: c++ sorting stl

我希望能够对以下矢量进行排序 - 矢量&lt;对&LT;字符串,对&lt; int,int&gt; &GT; &GT;基于该对的第一个元素&lt; int,int&gt;如果它们是相同的,那么根据它们的第二个元素对它们进行排序,我如何使用STL的结构在C ++中进行排序?

这种方法必须完成本

的内容

假设E1和E2是2个元素

如果E1.second.first == E2.second.first,则必须对第二个元素进行比较。

3 个答案:

答案 0 :(得分:2)

如果你不能使用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());
}

答案 1 :(得分:2)

  

[...]基于该对的第一个元素&lt; int,int&gt;如果这些是相等的,那么根据他们的第二个元素[...]

对它们进行排序

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

  

这是一个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;
    }
};

LIVE DEMO

#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)

答案 2 :(得分:0)

sort(x.begin, x.end, [](const X & a, const X & b){return a.second.first < b.second.first ; }) ;

其中x是您的容器,X是元素的类型。