1

I found this error and I just can't understand why it happens. I want to use a range-for to reset all the elements in a vector. The code below works for vector<int> but gives me a compilation error for vector<bool>.

Code:

#include <iostream>
#include <vector>

int main(){

  std::vector<int> vi (10,1);
  for(int &i : vi)
    i = 0;

  std::vector<bool> vb (10,1);
  for(bool &b : vb)
    b = 0;

  return 0;
}

Compilation output:

test.cc: In function ‘int main()’:
test.cc:11:17: error: cannot bind non-const lvalue reference of type ‘bool&’ to an rvalue of type ‘bool’
   11 |   for(bool &b : vb)
      |                 ^~
In file included from /usr/include/c++/9.3.0/vector:68,
                 from test.cc:2:
/usr/include/c++/9.3.0/bits/stl_bvector.h:86:5: note:   after user-defined conversion: ‘std::_Bit_reference::operator bool() const’
   86 |     operator bool() const _GLIBCXX_NOEXCEPT
      |     ^~~~~~~~

gscgomes
  • 91
  • 4

0 Answers0