Home >Backend Development >C++ >Why Can\'t I Use `auto&` with `std::vector` in a Range-for-Loop?
Range-for-Loops with std::vector
In C , range-for-loops are commonly used to iterate over STL containers. However, one might encounter an error when attempting to use this approach with a std::vector
Consider the following code snippet:
<code class="cpp">std::vector<int> intVector(10); for(auto& i : intVector) std::cout << i;</code>
This code works because std::vector
However, if we try to perform the same operation with a std::vector
<code class="cpp">std::vector<bool> boolVector(10); for(auto& i : boolVector) std::cout << i;</code>
This is because std::vector
Proxies are temporary objects that cannot be bound to an lvalue reference. This is why we cannot use auto& in the range-for-loop above. Instead, we need to use auto&&, which will correctly bind to an lvalue reference if given one or maintain the temporary Proxy alive if it's given a proxy. Here's the corrected code:
<code class="cpp">for(auto&& i : boolVector) std::cout << i;</code>
The above is the detailed content of Why Can\'t I Use `auto&` with `std::vector` in a Range-for-Loop?. For more information, please follow other related articles on the PHP Chinese website!