C++对的向量

C++ vector of pairs

本文关键字:向量 C++      更新时间:2023-10-16

我有一个对向量。我想以这样一种方式对配对进行排序,即它们之间差异最小的对是第一个元素。例如。

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

排序后:

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

我尝试过这样,但出现运行时错误:

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

我认为您的比较函数不正确。要实现排序,您需要以下内容:

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

您的比较运算符不好,因为它既不是传递的又不是非对称的。 传递本质上意味着,如果你有三对a,b和c,compare(a,b)为真,compare(b,c)为真,那么compare(a,c)应该是真的。不对称意味着如果compare(a,b)为真,那么compare(b, a)应该是假的。如果你想先通过差异进行比较,然后按字典顺序使用以下内容:

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

这是在 lambda 表达式中使用 C++14 自动功能的代码:

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

您可以使用例如 clang 编译它:

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