c++ - What's the difference between & and && in a range-based for loop? -
i'm wondering what's difference between for (auto& : v)
, for (auto&& : v)
in range-based loop in code:
#include <iostream> #include <vector> int main() { std::vector<int> v = {0, 1, 2, 3, 4, 5}; std::cout << "initial values: "; (auto : v) // prints initial values std::cout << << ' '; std::cout << '\n'; (auto : v) // doesn't modifies v because copy of each value std::cout << ++i << ' '; std::cout << '\n'; (auto& : v) // modifies v because reference std::cout << ++i << ' '; std::cout << '\n'; (auto&& : v) // modifies v because rvalue reference (am right?) std::cout << ++i << ' '; std::cout << '\n'; (const auto &i : v) // wouldn't compile without /**/ because const std::cout << /*++*/i << ' '; std::cout << '\n'; }
the output:
initial values: 0 1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6
2 3 4 5 6 7
2 3 4 5 6 7
both seem same thing here want know what's difference between for (auto& : v)
, for (auto&& : v)
in code.
this answer answer question, relevant part following:
auto => copy element, reference more efficient auto& => bind modifiable lvalues const auto& => bind make const, giving const_iterator const auto&& => bind rvalues
Comments
Post a Comment