I have a question regarding functors. I built a simple class:
class PolygonPrinter {
private:
std::vector<float> x;
std::vector<float> y;
public:
inline void operator()(Point& p) {
x.push_back(boost::geometry::get<0>(p));
y.push_back(boost::geometry::get<1>(p));
}
void printPoints() {
for(int i=0; i < x.size(); i++) {
std::cout << "("
<< x[i] << "," << y[i]
<< ")" << std::endl;
}
}
}
Which I wanted to use as a functor. This is used in something like
PolygonPrinter<point_2d> polyPrinter;
boost::geometry::for_each_point( polygon, polyPrinter );
polyPrinter.printPoints();
Now it seems the functor part works fine as I see the vectors being populated with all the polygon elements (so the for_each_point works as expected), however, the third call ( printPoints ) prints no points and in fact both vectors are empty. I guess this behaviour is expected, however, I cannot understand how the vectors are cleared. I thought you could have stateful functors.
Why are the vector fields x and y in the polyPrinter instance empty?
std
algorithms copy your functor. boost
probably does the same.
You can std::ref( functor )
to pass it via pseudo-ref, and you'll get the behaviour you want.
boost::geometry::for_each_point( polygon, std::ref(polyPrinter) );
As an aside, your use of inline
is redundant: all methods defined in the body of a class are implicitly inline
. This is the source of some fun to track down bugs.