对于C++sort(),如何将参数传递给自定义比较函数
For C++ sort(), how to pass a parameter to custom compare function?
我想使用标准排序函数,根据点与另一点的距离(例如重心)对点进行排序。
我知道我可以编写一个自定义的比较函数,但我不知道如何将参数传递给它。我希望它是线程安全的,所以我不想将参数存储在一个中心位置。有没有一种方法可以将额外的参数传递给自定义比较函数?
// Here is a compare function without a parameter for sorting by the x-coordinate
struct Point2fByXComparator {
bool operator ()(Point2f const& a, Point2f const& b) {
return a.x > b.x;
}
};
// Here is the outline of another comparator, which can be used to sort in respect
// to another point. But I don't know how to pass this other point to the compare
// function:
struct Point2fInRespectToOtherPointComparator {
bool operator ()(Point2f const& a, Point2f const& b) {
float distanceA = distance(a, barycenter);
float distanceB = distance(b, barycenter);
return distanceA > distanceB;
}
};
std::vector<Point2f> vec = ...;
Point2f barycenter(0, 0);
for (int i = 0; i < vec.size(); i++) {
barycenter += vec[i];
}
barycenter *= (1.0/vec.size());
// In the next line I would have to pass the barycenter to the compare function
// so that I can use the barycenter for comparison. But I don't know how to do
// this.
sort(vec.begin(), vec.end(), Point2fInRespectToOtherPointComparator());
记住结构和类几乎相同,请向类中添加一个成员。
struct Point2fBarycenterComparator {
explicit Point2fBarycenterComparitor(Point2f barycenter_)
: barycenter(barycenter_) {}
bool operator ()(Point2f const& a, Point2f const& b) const {
float distanceA = distance(a, barycenter);
float distanceB = distance(b, barycenter);
return distanceA > distanceB;
}
Point2f barycenter;
};
std::vector<Point2f> vec = ...;
Point2f barycenter = ...;
sort(vec.begin(), vec.end(), Point2fBarycenterComparator(barycenter));
您基本上已经有了一个函数对象,您所要做的就是在结构中添加一个构造函数,该构造函数接受您需要的参数,并将它们存储在成员变量中,以便运算符()使用。
相关文章:
- 参数化自定义CMake工具链
- 没有默认构造函数作为模板参数的自定义比较器
- C++ 通过函数传递自定义结构
- 为什么在类或结构中传递自定义比较器函数?
- 如何实现接受参数的自定义流操纵器?
- 将自定义对象作为参数从目标 C 传递到 C++
- 如何将参数传递到自定义比较C 中分类的函数
- 示例自定义共享_ptr-我如何传递构造函数参数 - 我在此处使用variadic模板
- 传递自定义函数类型时的'incompatible types in assignment'
- C ,在WXWIDGETS中传递自定义类对象
- 通过引用传递自定义优先级队列
- C++ 使用带有变量作为参数的自定义 ifstream 类时出错
- 通过函数传递自定义比较器
- 使用QGLShaderProgram从Qt传递自定义类型(结构体)统一到GLSL
- c++ STL std::random_shuffle不能传递自定义随机数生成器
- 如何使用命令参数从<自定义操作 /> 调用.exe文件
- c++中的QML回调,参数为自定义类型
- 传递自定义类来连接(信号和插槽)
- Cin参数到自定义类
- 通过引用传递自定义类型-任何性能优势