Let’s say I have a vector of Polygons, where each polygon contains a vector of Points. I have to iterate over all the points of all the polygons many times in my code, I end up having to write the same code over and over again:
for(std::vector<Polygon*>::const_iterator polygon = polygons.begin();
polygon != polygons.end(); polygon++)
{
for(std::vector<Point>::const_iterator point = (*polygon)->points.begin();
point != (*polygon)->points.end(); point++)
{
(*point).DoSomething();
}
}
I really feel that is a lot of code for two simple iterations, and feel like it’s clogging the code and interfering with the readability.
Some options I thought are:
- using #defines – but it would make unportable (to use in other parts of the code). Furthermore, #defines are considered evil nowadays;
- iterate over vector->size() – it doesn’t seem the most elegant way;
- calling a method with a function pointer – but in this case, the code that should be inside of the loop would be far from the loop.
So, what would be the most clean and elegant way of doing this?
In C++11, using ranged-base for loops and the
autokeyword: