简体   繁体   中英

C++ vector of pairs

I have a vector of pairs. I want to order the pairs in such a way that pair with the least difference between them is the first element. eg.

(1,10),(2,5), (5,8), (1,2), (8,10)

After sort:

(1,2), (8,10), (2,5), (5,8) , (1,10)

I tried like this but I am getting a run time error:

bool compare(const pair<int, int>&i, const pair<int, int>&j)
{
    if( (i.first-i.second) < (j.first-j.second) )
        return i.first < j.first ;
    else 
        return j.first < j.second;
}

I think your comparison function is incorrect. To achieve sorting you'd need something like:

bool compare(const pair<int, int>&i, const pair<int, int>&j)
{
    return abs(i.first-i.second) < abs(j.first-j.second);
}

Your comparison operator is not good as it is not both transitive and asymetric. Transitive essentially means that it if you have three pairs a,b and c for which compare(a,b) is true, compare(b,c) is true then compare(a,c) should be true. Asymmetric means that if compare(a,b) is true then compare(b, a) should be false. If you want to compare first by the difference and then lexicographically use someting of the sort of:

bool compare(const pair<int, int>&i, const pair<int, int>&j)
{
  if( (i.first-i.second) != (j.first-j.second) )
    return i.first - i.second< j.first - j.second;
  else 
    return i < j;
}

This is the code which makes use of C++14 auto feature in lambda expressions:

#include <vector>
#include <utility>
#include <cstdlib> // for std::abs(int)
#include <iostream>
#include <algorithm>


int main()
{
  using namespace std;

  vector<pair<int, int>> v = 
  { {1,10}
  , {2,5}
  , {5,8}
  , {1,2}
  , {8,10}
  };

  auto abs_distance = [](auto const& v) { return abs(v.first - v.second); };

  sort( v.begin(), v.end()
      , [&abs_distance](auto const& lhs, auto const& rhs)
        { return abs_distance(lhs) < abs_distance(rhs); }
      )
  ;

  for(auto const& p: v)
    cout << "("<< p.first << ", " << p.second << ") ";
  cout << endl;

  return 0;
}

You can compile it using, eg clang with:

clang++ -std=c++1y main.cpp

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