Home  >  Article  >  Backend Development  >  Why Do Range-Based For Loops Behave Differently with `std::vector`?

Why Do Range-Based For Loops Behave Differently with `std::vector`?

DDD
DDDOriginal
2024-10-30 04:06:02948browse

Why Do Range-Based For Loops Behave Differently with `std::vector`?

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, however, a unique behavior arises due to its underlying storage mechanism.

In the first example:

<code class="cpp">std::vector<int> intVector(10);
for (auto& i : intVector)
    std::cout << i;</code>

The std::vector contains integers, so the iterator type is an std::vector::iterator. This iterator dereferences to a T&, which in this case is int&, making the counter variable of type int&.

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 contains bools, which are stored in an integer-packed format. The iterator type is std::vector::iterator, which dereferences to a std::vector::reference, also known as a std::_Bit_reference. This reference type is an rvalue (temporary) and cannot be bound to a non-const reference. This results in the compilation error:

<code class="text">invalid initialization of non-const reference of type ‘std::_Bit_reference&amp;’ 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn