简体   繁体   中英

custom sort a vector 2d c++17 send to back

I know that we can sort a std::vector using c++17

but I want to customize this

currently, I'm doing this, v is vector<vector<int>>

v=[[10,125],[2,13],[3,2],[1,2]]

I want to sort this 2d vector in terms of summation of both numbers also I want to send those pairs to the end of the vector which has a higher first index than 2nd one ie if a[i][0]>a[i][1] send this pair to back/end of vector.

std::sort(v.begin(),v.end(),[](const vector<int> &a,const vector<int> &b){
            if(a[0]>a[1]){
                 //send to back        
            }
            if((a[0]+a[1])<(b[0]+b[1])){
                return 1;
            }else{
                 return 0;
            }
        });

I want the vector should look like

v=[[1,2],[2,13],[10,125],[3,2]]

I find the following style much easier to reason about. You've given two rules, in order of importance:

  1. Pairs with a particular ordering should be first.
  2. Otherwise, compare by the sum.
std::sort(v.begin(), v.end(), [](std::vector<int> &lhs, std::vector<int> &rhs) {
   const int lhs_sum = lhs[0] + lhs[1];
   const int lhs_order = lhs[0] > lhs[1];
   const int rhs_sum = rhs[0] + rhs[1];
   const int rhs_order = rhs[0] > rhs[1];

   return std::tie(lhs_order, lhs_sum) < std::tie(rhs_order, rhs_sum);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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