Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate through two std::lists simultaneously

Tags:

c++

iterator

std

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.

like image 451
Tom Swifty Avatar asked Nov 12 '13 15:11

Tom Swifty


People also ask

Can you loop through two lists at once Python?

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.

How do you iterate through a std queue?

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.


2 Answers

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!

like image 136
masoud Avatar answered Nov 10 '22 03:11

masoud


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.

like image 34
NPE Avatar answered Nov 10 '22 05:11

NPE