0

Why does

std::vector<int> v{1,2,3};
for (int& e : v){
    e = 5;
    std::cout << e << std::endl;
}

compile fine, while

std::vector<bool> v2{false, false, false};
for(bool& e : v2){
    if(e){
        std::cout << "True\n";
    }
}

creates a compile error

error: non-const lvalue reference to type 'bool' cannot bind to a temporary of type 'std::__1::__bit_iterator<std::__1::vector<bool, std::__1::allocator<bool> >, false, 0>::reference' (aka 'std::__1::__bit_reference<std::__1::vector<bool, std::__1::allocator<bool> >, true>')

The only thing that changes is the type from int to bool?

Jiddoo
  • 1,091
  • 2
  • 9
  • 14
  • 4
    Yes, [`vector` is special](https://stackoverflow.com/questions/17794569/why-isnt-vectorbool-a-stl-container). – Lukas-T Feb 12 '21 at 20:01
  • Actually, you changed a few things between the two. First: `e=5`, second: `if(e)`. First: `cout << e`, second: `cout << "True\n"`. I don't think that matters, but just noting because you said *The only thing that changes is the type from int to bool?* – Lakshya Raj Feb 12 '21 at 20:02
  • @AustinBrunkhorst Not `std::bitset`, no. Its length must be known at compile-time. – HolyBlackCat Feb 12 '21 at 20:03

0 Answers0