C++: Proper way to iterate over STL containers

后端 未结 8 1397
灰色年华
灰色年华 2021-01-06 04:55

In my game engine project, I make extensive use of the STL, mostly of the std::string and std::vector classes.

In many cases, I have to ite

8条回答
  •  隐瞒了意图╮
    2021-01-06 05:47

    Native for-loop (especially index-based) - it's C-way, not C++-way.

    Use BOOST_FOREACH for loops.

    Compare, for container of integers:

    typedef theContainer::const_iterator It;
    for( It it = theContainer.begin(); it != theContainer.end(); ++it ) {
        std::cout << *it << std::endl;
    }
    

    and

    BOOST_FOREACH ( int i, theContainer ) {
        std::cout << i << std::endl;
    }
    

    But this is not perfect way. If you can do your work without loop - you MUST do it without loop. For example, with algorithms and Boost.Phoenix:

    boost::range::for_each( theContainer, std::cout << arg1 << std::endl );
    

    I understand that these solutions bring additional dependencies in your code, but Boost is 'must-have' for modern C++.

提交回复
热议问题