Home > Backend Development > C++ > Why Can\'t I Use `auto&` with `std::vector` in a Range-for-Loop?

Why Can\'t I Use `auto&` with `std::vector` in a Range-for-Loop?

Barbara Streisand
Release: 2024-10-27 05:28:03
Original
669 people have browsed it

Why Can't I Use `auto&` with `std::vector` in a Range-for-Loop?

Range-for-Loops with std::vector

In C , range-for-loops are commonly used to iterate over STL containers. However, one might encounter an error when attempting to use this approach with a std::vector.

Consider the following code snippet:

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

This code works because std::vector is a container with iterators that dereference to an int&. This means that we can bind the dereferenced value of the iterator to our own lvalue reference auto&.

However, if we try to perform the same operation with a std::vector, we will encounter an error similar to:

<code class="cpp">std::vector<bool> boolVector(10);
for(auto& i : boolVector)
    std::cout << i;</code>
Copy after login

This is because std::vector is not a container in the traditional sense but rather a bitset. It stores boolean values in a packed manner, using integers to represent multiple booleans. As a result, its iterators return a Proxy object instead of a bool&.

Proxies are temporary objects that cannot be bound to an lvalue reference. This is why we cannot use auto& in the range-for-loop above. Instead, we need to use auto&&, which will correctly bind to an lvalue reference if given one or maintain the temporary Proxy alive if it's given a proxy. Here's the corrected code:

<code class="cpp">for(auto&& i : boolVector)
    std::cout << i;</code>
Copy after login

The above is the detailed content of Why Can\'t I Use `auto&` with `std::vector` in a Range-for-Loop?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template