Tom Swifty
Tom Swifty

Reputation: 2952

iterate through two std::lists simultaneously

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.

Upvotes: 9

Views: 20110

Answers (4)

GMasucci
GMasucci

Reputation: 2892

It is reasonable to do it the way you have, there are some other approaches you could take to minimise the amount of checks being done:

If you have already checked both lengths are equal (as stated as a prior check), a standard for loop may well suffice, which eliminates the access of two variables and relies only on the increment of one variable:

for (int i = 0; i< l1.size();i++)
{
    // run some code here
}

However you would need to use advance() or next() to march through the objects in the list within the "some code here".

Upvotes: 1

masoud
masoud

Reputation: 56479

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!

Upvotes: 15

MarkB
MarkB

Reputation: 882

If you are doing a simple operation on each pair of objects, you can use std::transform.

Upvotes: 1

NPE
NPE

Reputation: 500475

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.

Upvotes: 1

Related Questions