矢量对按对元素

时间:2017-08-14 15:22:41

标签: c++ sorting

在C ++中是否有任何方法,这将根据对值的差异为我排序一对向量。举个例子,假设我有4对

1 3, 
5 6, 
2 3,
12 5,

所以,对的差异是2 1 1 7,如果我按降序排序则排序的矢量将是,

12 5,
1 3,
5 6,
2 3,

我希望你明白我的问题是什么。有没有办法按这种方式对元素进行排序?

我试过这种方法来根据第一个或第二个元素对元素进行排序。但这不是我的问题。我的问题是我需要根据差异进行排序。

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


int main()
{
    vector< pair <int,int> > pq;
    for(int i=1; i<=4; i++){
        int x,y;
        cin >> x >> y;

        pq.push_back(make_pair(x,y));
    }

    sort(pq.begin(), pq.end(), sortinrev);

    for(int i=0; i<4; i++){
        cout << pq[i].first << " " << pq[i].second << endl;
    }


    return 0;
}

3 个答案:

答案 0 :(得分:8)

如果您的容器是

std::vector<std::pair<int, int>> data;

您可以将其排序为

std::sort(std::begin(data),
          std::end(data),
          [](std::pair<int, int> const& lhs, std::pair<int, int> const& rhs)
          {
              return std::abs(lhs.first - lhs.second) < std::abs(rhs.first - rhs.second);
          });

如果您想在升序和降序之间切换,只需相应地从<切换到>

答案 1 :(得分:2)

标准库提供了数据结构std::pair和排序算法std::sort,您可以向其传递定义顺序的自定义比较。请参阅以下代码,该代码定义了一个比较器,其中包含两个std::pair<int,int>并根据它们的“绝对差异”进行比较,以及如何使用它调用std::sort的代码。希望能帮助到你。

#include <iostream>
#include <vector>

int main()
{
    std::vector<std::pair<int,int> > v = {
        {1, 3},
        {5, 6},
        {2, 3},
        {12, 5}
    };

    // sort using a custom function object
    struct {
        bool operator()(const std::pair<int,int> &a, const std::pair<int,int> &b) const
        {
            return ( abs(a.first-a.second) > abs(b.first-b.second));
        }
    } differenceIsGreater;
    std::sort(v.begin(), v.end(), differenceIsGreater);
    for (auto a : v) {
        std::cout << "(" << a.first << "," << a.second << ")" << std::endl;
    }

    return 0;
}

输出:

(12,5)
(1,3)
(5,6)
(2,3)

答案 2 :(得分:1)

std :: sort有一个带有比较可调用的重载。

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

因此,您可以将lambda(或其他函数)作为第三个参数传递,以便以任何方式进行比较。

来自cppreference.com:

comp     -   comparison function object (i.e. an object that satisfies the     requirements of Compare) which returns ​true if the first argument is less than (i.e. is ordered before) the second. 
The signature of the comparison function should be equivalent to the following:

bool cmp(const Type1 &a, const Type2 &b);

The signature does not need to have const &, but the function object must not modify the objects passed to it.
The types Type1 and Type2 must be such that an object of type RandomIt can be dereferenced and then implicitly converted to both of them. ​

所以,例如

sort(begin(myvect), end(myvect), [](auto p) { /* comparison code */ });

(这需要c ++ 14,您可能需要根据编译器版本进行修改)

相关问题