簡體   English   中英

如何對矢量進行排序 <pair<string , pair<int , int> &gt;&gt;?

[英]How to sort a vector<pair<string , pair<int , int>>>?

我希望能夠根據對<int,int>對的第一個元素對以下向量進行排序 - vector <pair <string,pair <int,int> >>,如果它們相等,則根據它們的第二個對它們進行排序元素,我如何使用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());
}

[...]基於對<int,int>對的第一個元素,如果它們相等,那么根據它們的第二個元素[...]對它們進行排序

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;
    }
};

現場演示

#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是元素的類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM