矢量对按对元素的差异排序

Yea*_*man 4 c++ sorting

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

1 3, 
5 6, 
2 3,
12 5,
Run Code Online (Sandbox Code Playgroud)

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

12 5,
1 3,
5 6,
2 3,
Run Code Online (Sandbox Code Playgroud)

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

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

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;
}
Run Code Online (Sandbox Code Playgroud)

Cor*_*mer 8

如果你的容器是

std::vector<std::pair<int, int>> data;
Run Code Online (Sandbox Code Playgroud)

你可以把它整理成

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);
          });
Run Code Online (Sandbox Code Playgroud)

如果要在升序和降序之间切换,只需相应切换<即可>.

  • 你的代码非常适合这种情况,但如果OP不知道如何查找并找到这种排序函数,我怀疑他会理解lambdas.也许添加一个解释?或者使比较器具有自己的功能? (3认同)