2

In the simple code below for (auto& v : vb) does not compile whereas for (auto & v : vi) compiles fine.

The only difference is that vb is a vector of bool and vi is a vector of int.

The error message:

error C2440: 'initializing': cannot convert from 'std::_Vb_referencestd::_Wrap_alloc<std::allocator<std::_Vbase>>' to 'std::_Vb_referencestd::_Wrap_alloc<std::allocator<std::_Vbase>> &'`

is not really helpful for me.

#include <vector>

int main()
{
  std::vector<bool> vb{ false, false };
  for (auto & v : vb)  //<<< error messages refers to this line
    v = true;   
  
  std::vector<int> vi{ 1, 2 };
  for (auto & v : vi)  //<<< compiles fine
    v = 2;
}

bool being a builtin C++ type (basically a special kind of char), both range based loops should compile.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • 6
    `std::vector` does some fancy stuff to pack bools into a bitfield. As a result, dereferencing iterators return some proxy object and not just a `bool&`. Many complain about the standard making so, but this cannot be changed due to backward compatibility. Consider using `std::vector` or adjust your code to account for the existence of those proxy objects. – CygnusX1 Sep 24 '21 at 08:29
  • 1
    @JeJo I know, the question was specifically about bool vs int. And the [duplicate](https://stackoverflow.com/questions/34079390/range-for-loops-and-stdvectorbool) and the first comment perfectly address it. – Jabberwocky Sep 24 '21 at 08:41

0 Answers0