For a C++ project, I have a vector with custom objects that have a method getX()
to get their x value.
I have a method that needs to loop over all elements where property x is between startX
and endX
.
What is the correct way to loop over those items?
Currently I have:
int startX = 20;
int endX = 30
for(SomeClass x: someObject->getObjects())
{
if(x->getX() > startX && x->getX() < endX)
{
//do something
}
}
It works fine, but I remember from an old C++ lesson that there was a method that loops over the elements more efficiently.
I remember something like:
int startX = 20;
int endX = 30
for(SomeClass x : find(someObject->getObjects(), x, x->getX() > startX && x->getX() < endX)
{
//do something
}
Where I only iterate over the elements that I need and the check is not inside of the loop anymore.
edit: I changed the qt foreach loop to a for loop to avoid discussion about that part.