Iterate through two std :: list at the same time

Sorry if this is too easy a question.

Preliminary error checking provides 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 smart approach or is there a more elegant solution? Thank you for your help.

+4
source share
4 answers

I prefer to use forif increments are unconditionally executed:

for(; it1 != l1.end() && it2 != l2.end(); ++it1, ++it2)
{
    //run some code
}

You can omit one test, while the size of the lists is the same, but I'm not sure what happens in the execution of some code!

+7
source

I think this is quite reasonable (except that I will use pre-increment, not post-increment).

"zip iterator" , , .

+1

, std::transform.

+1

, , , , :

, ( ), , :

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

advance() next() " ".

+1

All Articles