使用自定义比较函数进行C 排序
c++ sorting with custom compare function
我有一个以下类型的向量:
std::vector< std::pair< std::pair< int, int >, std::vector<float> > > neighbors;
我想创建以下分类以下向量
std::sort( neighbors.begin(), neighbors.end(), myFunc(index) );
在哪里,
bool myFunc( const std::pair< std::pair< int, int >, float > &a, const std::pair< std::pair< int, int >, float > &b, const int index ){
return ( a.second[index] > b.second[index] );
}
我知道语法是错误的,但我希望提供一个索引以比较向量的元素。
我不确定如何将此参数传递给myfunc。
lambdas:
std::sort(
neighbors.begin(),
neighbors.end(),
[index](const std::pair< std::pair< int, int >, std::vector<float> > &a,
const std::pair< std::pair< int, int >, std::vector<float> > &b)
{
return ( a.second[index] > b.second[index] );
}
);
查看C 11中的lambda表达式是什么?用于介绍。
pre-c 11解决方案:使用对象实例作为自定义比较器
struct Comparator {
Comparator(int index) : index_(index) {}
bool operator () (const std::pair< std::pair< int, int >, std::vector<float> > &a,
const std::pair< std::pair< int, int >, std::vector<float> > &b)
{
return ( a.second[index_] > b.second[index_] );
}
int index_;
};
sort(neighbors.begin(), neighbors.end(), Comparator(42));
C 11 解决方案:使用lambda
std::sort(neighbors.begin(), neighbors.end(), [index]
(const std::pair< std::pair< int, int >, std::vector<float> > &a,
const std::pair< std::pair< int, int >, std::vector<float> > &b)
{
return ( a.second[index] > b.second[index] );
}
);
我的建议:如果允许使用C 11功能,请选择Lambda。它可能更优雅和可读。
相关文章:
- 如何计算此排序函数的时间复杂度?
- 什么是自定义比较器以及如何在 C++ 的排序函数中使用它?
- 自定义排序函数中的堆溢出
- 分段 排序函数实现中的错误
- 使用排序函数 c++ 对字符数组进行排序
- 类中的排序函数
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- 快速排序函数在快速排序算法中如何工作?
- 解释标准库排序函数C++的比较谓词的工作原理?
- C++ wrt 字符串中的 STL 排序函数
- 排序函数和优先级队列 C++ 中的比较器
- 为什么当我们使用等于'='符号比较器函数时,c ++的内置排序函数不起作用?
- C++排序函数中的奇怪之处
- C++ 排序函数中的数组项赋值
- 瓶颈 C++ 排序函数Wi-Fi 信号
- 算法中的排序函数返回错误
- 排序函数如何在整数对的向量上工作?
- 从递归向后选择排序函数调用 max 和交换函数
- 排序函数未正确返回数组
- 如何将比较器添加到自定义排序函数