Custom comparator that depends on an external value
I want to have a set of points sorted by the distance to the third point. Is something like this possible?
I tried this but it doesn't work:
struct compStruct {
Point point;
bool operator()(const Point & a, const Point & b) const { return length(a-point)<length(b-point); }
};
void f(const Point & point) {
compStruct cs;
cs.point = point;
std::set<Point, &cs.operator()> pointSet;
}
I cannot use a lambda because I want to use this set as an argument to another function. So this doesn't work:
void g(std::set<Point, pointComp>) {}
void f(const Point & point) {
auto pointComp = [&](const Point & a, const Point & b){ return length(a-point)<length(b-point); };
std::set<Point, pointComp> s;
g(s);
}
+3
source to share
2 answers
Your first example should work if you change the way you declare the instance std::set
:
std::set<Point, compStruct> pointSet(cs);
The template does not restrict the use of the function type; you can specify a class to use as a comparator.
Edit - Updated the example to pass the comparator instance correctly.
+2
source to share
Use std::function
:
#include <functional>
using Cmp = std::function<bool(const Point & a, const Point & b)>;
void g(std::set<Point, Cmp>) {}
void f(const Point & point)
{
auto pointComp = [&](const Point & a, const Point & b){ return length(a-point)<length(b-point); };
std::set<Point, Cmp> s(pointComp);
g(s);
}
+1
source to share