Home >Backend Development >C++ >Why Does Using Range-Based Loops with std::vector Result in a Compiler Error?
In C , range-based loops have become widespread for their simplicity and readability. They iteratively iterate over elements of sequences or container objects.
However, a curious inconsistency arises when attempting to use range-based loops with std::vector
<code class="cpp">std::vector<int> intVector(10); for(auto& i : intVector) std::cout << i;</code>
using range-for-loops with std::vector
<code class="cpp">std::vector<bool> boolVector(10); for(auto& i : boolVector) std::cout << i;</code>
The error message "invalid initialization of non-const reference of type 'std::_Bit_reference&' from an rvalue of type 'std::_Bit_iterator::reference {aka std::_Bit_reference}'" indicates that a non-const reference is being initialized with an rvalue.
Understanding the Issue
The reason for this discrepancy lies in the distinct implementation of std::vector
Solution: Using auto&&&
To resolve this issue, it is necessary to use auto&&& instead of auto&. This idiom will correctly collapse the reference to an lvalue reference when provided with an lvalue (such as intVector in the first example), while simultaneously binding and maintaining the temporary alive if a proxy is provided (as in the case of boolVector).
<code class="cpp">for(auto&& i : boolVector) std::cout << i;</code>
By employing this technique, you can effectively iterate over std::vector
The above is the detailed content of Why Does Using Range-Based Loops with std::vector Result in a Compiler Error?. For more information, please follow other related articles on the PHP Chinese website!