Range-for-Loops and std::vector
When using range-based for loops with standard library containers, the data type of the iterator often dictates the data type of the counter variable. In the case of std::vector
In the first example:
<code class="cpp">std::vector<int> intVector(10); for (auto& i : intVector) std::cout << i;</code>
The std::vector
Now, let's consider the second example:
<code class="cpp">std::vector<bool> boolVector(10); for (auto& i : boolVector) std::cout << i;</code>
Here, the std::vector
<code class="text">invalid initialization of non-const reference of type ‘std::_Bit_reference&’ from an rvalue of type ‘std::_Bit_iterator::reference {aka std::_Bit_reference}’</code>
The solution is to use auto&&, which will bind to an lvalue reference if it's an lvalue reference, or create a temporary copy of the rvalue if it's a temporary:
<code class="cpp">for (auto&& i : boolVector) std::cout << i;</code>
With this modification, the code will output the contents of boolVector as expected.
The above is the detailed content of Why Do Range-Based For Loops Behave Differently with `std::vector`?. For more information, please follow other related articles on the PHP Chinese website!