Initial value of non-const reference must be lvalue C++ [duplicate]

  c++, class

I wanted to do some initialization in the constructor: first extending the vector size to n, then setting all of its elements to false.

Yet all that pops out is what is described in the title: "Initial value of non-const reference must be lvalue".

I tried another means of using the regular for as follows:

for (int i=0; i<n; i++)
    visited[i]=false;

and it worked out fined enough. However, it still puzzles me why the other means is invalid.

#include <iostream>
#include <list>
#include <vector>

using namespace std;

class graph
{
    public:
        vector<list<int> > vertex;
        vector<bool> visited;

        graph(int n): vertex(n), visited(n)
        {
            for (bool &b: visited)
                b=false;
        }
};

int main()
{
    
}

Source: Windows Questions C++

LEAVE A COMMENT