Sorry if this is too simple a question.
Prior error checking ensures l1.size() == l2.size()
.
std::list<object1>::iterator it1 = l1.begin();
std::list<object2>::iterator it2 = l2.begin();
while(it1 != l1.end() && it2 != l2.end()){
//run some code
it1++;
it2++;
}
Is this a reasonable approach, or is there a more elegant solution? Thanks for your help.
Example 2: Using itertools (Python 2+)Using the zip_longest() method of itertools module, you can iterate through two parallel lists at the same time. The method lets the loop run until the longest list stops.
If you need to iterate over a std::queue , you can create a copy of it and remove items from the copy, one at a time, using the standard pop function after processing it. This way the original queue remains untouched, but its copy becomes empty.
I prefer to use for
if increments unconditionally occurs:
for(; it1 != l1.end() && it2 != l2.end(); ++it1, ++it2)
{
//run some code
}
You can omit one test while the size of lists are the same, but I'm not sure what's going on in run some code!
I think this is perfectly reasonable (except that I'd use pre-increment rather than post-increment).
You could consider using a "zip iterator" of some sort, but it's not totally obvious that this would be worth the hassle in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With