C++11 Range-based for-loop efficiency “const auto &i” versus “auto i”

后端 未结 3 1579
耶瑟儿~
耶瑟儿~ 2020-12-07 13:15

In C++11, I can iterate over some container like so:

for(auto i : vec){
   std::cout << i << std::endl;
}

But I know that this

3条回答
  •  离开以前
    2020-12-07 13:41

    Imagine if your vector contains strings. Long strings. 5000 long strings. Copy them unnecessarily and you end up with a nicely written for loop that is awfully inefficient.

    Make sure your code follows your intention. If you do not need a copy inside of the loop, do not make one.

    Use a reference & as suggested above, or iterators.

提交回复
热议问题