iterate through two std::lists simultaneously

戏子无情 提交于 2019-12-05 08:01:00

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 are doing a simple operation on each pair of objects, you can use std::transform.

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

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