iterate through two std::lists simultaneously

橙三吉。 提交于 2019-12-07 01:52:43

问题


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.


回答1:


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!




回答2:


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.




回答3:


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




回答4:


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".



来源:https://stackoverflow.com/questions/19933537/iterate-through-two-stdlists-simultaneously

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!