Range-for-loops and std::vector

前端 未结 3 1672
我在风中等你
我在风中等你 2020-11-28 10:16

Why does this code work

std::vector intVector(10);
for(auto& i : intVector)
    std::cout << i;

And this doesn\'t?

<
3条回答
  •  心在旅途
    2020-11-28 11:02

    Because std::vector is not a container !

    std::vector's iterators usually dereference to a T&, which you can bind to your own auto&.

    std::vector, however, packs its bools together inside integers, so you need a proxy to do the bit-masking when accessing them. Thus, its iterators return a Proxy.
    And since the returned Proxy is an prvalue (a temporary), it cannot bind to an lvalue reference such as auto&.

    The solution : use auto&&, which will correctly collapse into an lvalue reference if given one, or bind and maintain the temporary alive if it's given a proxy.

提交回复
热议问题