C++ STL: Which method of iteration over a STL container is better?

后端 未结 9 1015
轻奢々
轻奢々 2020-12-09 11:43

This may seem frivolous to some of you, but which of the following 2 methods of iteration over a STL container is better? Why?



        
9条回答
  •  萌比男神i
    2020-12-09 11:55

    Method 0, for several reasons.

    • It better expresses your intent, which aids compiler optimizations as well as readability
    • Off-by-one errors are less likely
    • It works even if you replace the vector with a list, which doesn't have operator[]

    Of course, the best solution will often be solution 2: One of the std algorithms. std::for_each, std::transform, std::copy or whatever else you need. This has some further advantages:

    • It expresses your intent even better, and allows some significant compiler optimizations (MS's secure SCL performs bounds checking on your methods 0 and 1, but will skip it on std algorithms)
    • It's less code (at the call site, at least. Of course you have to write a functor or something to replace the loop body, but at the use site, the code gets cleaned up quite a bit, which is probably where it matters most.

    In general, avoid overspecifying your code. Specify exactly what you want done, and nothing else. The std algorithms are usually the way to go there, but even without them, if you don't need the index i, why have it? Use iterators instead, in that case.

提交回复
热议问题