0

I am seeing a situation where changing the type of vector elements from int to bool makes the code stop compiling. What am I missing?

This code compiles fine:

#include <vector>

int main()
{
    std::vector<int> v(10);
    for (auto& e : v)   e = 1;
}

While for this code, the compiler (VC++ 2017) complains about constness mismatch:

#include <vector>

int main()
{
    std::vector<bool> v(10);
    for (auto& e : v)   e = true;
}

I realize that switching to auto&& fixes the problem, but I would appreciate a good explanation as to why.

PlinyTheElder
  • 1,454
  • 1
  • 10
  • 15
  • You can't take a reference to the elements with the `std::vector` specialization. – πάντα ῥεῖ Sep 20 '18 at 01:27
  • 2
    [`std::vector`](https://en.cppreference.com/w/cpp/container/vector_bool) is special. Implementations are allowed to specialize it such that each `bool` takes 1 bit. But to achieve this, it needs to break many guarantees and expectations of `std::vector`. Many people would say that this decision was a mistake, notably because it breaks code like the one you wrote. – François Andrieux Sep 20 '18 at 01:41

0 Answers0