0

I just learned range based for loops in c++ and i'm trying to create a function that initializes a vector to all 0's; i did the following:

#include <vector>
// #include <algorithm>
// #include <bits/stdc++.h>
using namespace std;

void init(vector<bool> & vec)
{
    for (auto &v : vec)
        v = 0;
}

int main()
{   
    vector<bool> vec = {0, 1, 0, 1, 1, 0};
    init(vec);

    return 0;
}

and the error is the following: `

error: cannot bind non-const lvalue reference of type ‘std::_Bit_reference&’ to an rvalue of type ‘std::_Bit_iterator::reference’ {aka ‘std::_Bit_reference’}
    8 |  for (auto &v : vec)
      |                 ^~~

i've search everything and i don't know why there is a problem with my code. the problem seems to be because v is a reference and everything is in a function; if i put everyting to main(), there will be no problem. what am i doing wrong?

the compiler i'm using is Ubuntu 9.4.0-1ubuntu1~20.04.1.

midi
  • 11
  • 3
    [`vector` is special](https://en.cppreference.com/w/cpp/container/vector_bool). It is not guaranteed to store actual `bool` elements in its inner array, so you can't take `bool&` references to its elements. – Remy Lebeau May 10 '23 at 16:59
  • 1
    `std::vector` is an exceptional case, its elements are not references to `bool`. – 273K May 10 '23 at 16:59
  • Change to `std::deque` and magically, things will start to work. – PaulMcKenzie May 10 '23 at 17:09
  • You could use `vec.assign(vec.size(), false);` and not have to write the function yourself. – BoP May 10 '23 at 17:37
  • Good that you commented out this horrible `#include `. Better would have been to remove it completely and forget its existence. – prapin May 10 '23 at 18:15
  • fwiw `for (auto&& v : vec)` should work. (edit, yes it's said in linked answer) – apple apple May 10 '23 at 18:46
  • it'd also work if you're using some kind of `move_iterator` (although not strictly equal to this case) – apple apple May 10 '23 at 18:48

0 Answers0