Home > Article > Backend Development > Why Does Using a Range-Based For Loop on `std::vector` Cause an Error?
Understanding Range-for-Loops and std::vector
In C , range-based for loops simplify the iteration over containers. However, unexpected behavior can arise when attempting to use these loops with certain container types, such as 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 iterates over the intVector collection and prints each element. However, replace intVector with a std::vector
<code class="cpp">std::vector<bool> boolVector(10); for(auto& i : boolVector) std::cout << i;</code>
This modified code results in an 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}’
Underlying Mechanism:
The discrepancy arises because std::vector
std::vector
Solution:
To resolve this, use auto&&& in the range-based loop:
<code class="cpp">for(auto&& i : boolVector) std::cout << i;</code>
The auto&&& syntax checks the type of the iterator reference. If it's an lvalue reference, it remains the same; otherwise, it binds to and preserves the temporary proxy, allowing the code to execute correctly.
The above is the detailed content of Why Does Using a Range-Based For Loop on `std::vector` Cause an Error?. For more information, please follow other related articles on the PHP Chinese website!