C++ iterators & loop optimization

前端 未结 11 1358
渐次进展
渐次进展 2021-01-30 04:11

I see a lot of c++ code that looks like this:

for( const_iterator it = list.begin(),
     const_iterator ite = list.end();
     it != ite; ++it)
<
11条回答
  •  耶瑟儿~
    2021-01-30 04:35

    I always preferred the first one. Though with inline functions, compiler optimizations and relatively smaller container size ( in my case it's normally max 20-25 items) it really does not make any large difference with respect to performace.

    const_iterator it = list.begin();
    const_iterator endIt = list.end();
    
    for(; it != endIt ; ++it)
    {//do something
    }
    

    But recently I am using more of std::for_each wherever it's possible. Its optimized looping which helps to make the code look more readable than other two.

    std::for_each(list.begin(), list.end(), Functor());
    

    I will use the loop only when std::for_each cannot be used. (for ex: std::for_each does not allow you to break the loop unless an exception is thrown).

提交回复
热议问题