C++对的向量
C++ vector of pairs
我有一个对向量。我想以这样一种方式对配对进行排序,即它们之间差异最小的对是第一个元素。例如。
(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
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 矩阵向量乘法(cublasDgemv)返回零
- 一对向量构造函数:初始值设定项列表与显式构造
- 将结构向量排序为子组
- 在C++中调整向量中的索引
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么