Range based for loop in function as reference throws error (C++)

51 Views Asked by At

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.

0

There are 0 best solutions below