mercredi 18 mars 2015

c++ stateful functor that populates vectors


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.


If someone could explain why the vector fields x and y in the polyPrinter instance are empty it would be great.


Cheers




Aucun commentaire:

Enregistrer un commentaire