Cause an Error in C ? " />
In C , range-based for loops provide a convenient way to iterate through elements in a container. However, certain behaviors may seem surprising when used with containers of boolean values.
Consider the following code:
<code class="cpp">std::vector<int> intVector(10); for (auto& i : intVector) std::cout << i; std::vector<bool> boolVector(10); for (auto& i : boolVector) std::cout << i;</code>
The first loop successfully iterates through the intVector and prints the integer elements. However, the second loop results in the following error:
error: invalid initialization of non-const reference of type ‘std::_Bit_reference&’ from an rvalue of type ‘std::_Bit_iterator::reference {aka std::_Bit_reference}’ for (auto& i : boolVector)
This error occurs because std::vector
To iterate through a std::vector
<code class="cpp">for (auto&& i : boolVector) std::cout << i;</code>
By using auto&&, the compiler will correctly collapse into an lvalue reference if given true boolean value references or bind and keep alive the temporary proxies if given references to proxies.
The above is the detailed content of Why Does Using a Range-Based For Loop With std::vector