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

后端 未结 3 1588
耶瑟儿~
耶瑟儿~ 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 14:06

    Disclaimer: In general the difference between auto and auto& is subtle, partly a matter of style, but sometimes also a matter of correctness. I am not going to cover the general case here!

    In a range based for loop, the difference between

    for (auto element : container) {}
    

    and

    for (auto& element_ref : container) {}
    

    is that element is a copy of the elements in the container, while element_ref is a reference to the elements in the container.

    To see the difference in action, consider this example:

    #include 
    
    int main(void) {
        int a[5] = { 23,443,16,49,66 };
    
        for (auto i : a) i = 5;       
        for (const auto& i : a) std::cout << i << std::endl;
        for (auto& i : a) i = 5;   
        for (const auto& i : a) std::cout << i << std::endl;    
    }
    

    It will print

    23
    443
    16
    49
    66
    5
    5
    5
    5
    5
    

    because the first loop works on copies of the array elements, while the second actually modifies the elements in the array.

    If you dont want to modify the elements then often a const auto& is more appropriate, because it avoids copying the elements (which can be expensive).

提交回复
热议问题