gpt4 book ai didi

c++ - 如何为 STL 排序编写带有中间变量的比较器

转载 作者:行者123 更新时间:2023-11-30 01:27:46 28 4
gpt4 key购买 nike

class Point    
{
int x;
}
static Point referencePoint;
struct Comparator
{
bool AbsComparator(const Point& p1, const Point& p2)
{
return abs(p1.x - referencePoint.x) < abs(p2.x - referencePoint.x);
}
};
list<Point> points;
points.sort(Comparator::AbsComparator);

但是我不能为多线程安全使用静态引用点,还有其他方法吗??谢谢。

最佳答案

让它成为Comparator的一部分:

struct Comparator
{
Point referencePoint;

Comparator(Point referencePoint): referencePoint(referencePoint) {}

Comparator(const Comparator& rhs) {
referencePoint = rhs.referencePoint;
}

bool operator()(const Point& p1, const Point& p2) const
{
return abs(p1.x - referencePoint.x) < abs(p2.x - referencePoint.x);
}
};

...

points.sort(Comparator(refP));

关于c++ - 如何为 STL 排序编写带有中间变量的比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8340641/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com