C++ 如何使用标准::根据类函数使用比较器
C++ How to use std::sort with comparator based on your class' function
我试图根据函数 calculateDistance() 返回的值对我的向量进行排序,该函数返回双精度值。我想问题是由排列Copmarator方法引起的。.cpp文件如下所示:
bool TSPgenetic::permutationComparator(int* i, int* j){
return calculateDistance(i) < calculateDistance(j);
}
void TSPgenetic::chooseNewPopulation(){
sort(population->begin(), population->end(), permutationComparator);
sort(children->begin(), children->end(), permutationComparator);
`....`
}
头文件片段:
bool permutationComparator(int*, int*);
传递
permutationComparator
作为std::sort
的第三个参数是无效的。只有static
类成员是有效的,并且是函子对象。要解决此问题,这里有四个选择:
使用 lambda 表达式创建一个闭包对象并在那里进行比较。
std::sort(population->begin(), population->end(), [](const int *i1, const int *i2){return calculateDistance(i1) < calculateDistance(i2);});
如果你的比较函数不需要
static
,你可以使用std::bind
。auto comp_func = std::bind(&TSPgenetic::permutationComparator, this, std::placeholders::_1, std::placeholders::_2); std::sort(population->begin(), population->end(), comp_func);
如果可能的话,将您的比较函数设为
static
。
重载类中的
bool operator () ( const int *i1, const int *i2 )
,以便类成为函子对象。
请注意,从逻辑上讲,比较函数不应是成员函数。它是一个接受两个对象并确定其顺序的函数。因此,几乎所有情况下,只有第三种选择适用。
相关文章:
- 函数类作为比较器
- 什么是自定义比较器以及如何在 C++ 的排序函数中使用它?
- 没有默认构造函数作为模板参数的自定义比较器
- 对没有比较器或λ函数的向量进行排序?
- 使用迭代器的自定义比较器函数
- 用于基于成员字段或函数创建比较器的快捷方式
- 为什么在类或结构中传递自定义比较器函数?
- std::用派生类对象设置,但用gcc8.1设置基类比较器
- 排序函数和优先级队列 C++ 中的比较器
- 为什么当我们使用等于'='符号比较器函数时,c ++的内置排序函数不起作用?
- 为模板类中的特定类型编写比较器函数
- 调用父类函数来比较父类和子类
- 无法使用比较器初始化标准::函数
- 通过函数指针对类内的 STL SET 使用自定义比较器
- 如何在类中从排序调用比较器函数C++
- C++ 如何使用标准::根据类函数使用比较器
- C++ unordered_set 用户定义类的比较器函数
- 调用 std::等于时出错,将类成员函数作为比较器
- 为什么函数比较器不像在排序中那样在优先级队列中工作?
- 使用自定义比较器函数在类中定义优先级队列