1

When I try to compile my code containing this fragment:

vector<vector<bool>> p(n);
for(vector<bool>& i : p) {
    i = vector<bool>(m);
}

for(vector<bool>& i : p) {
        for(bool& j : i) {
            int a = round(rand() / double(RAND_MAX));
            if(a) j = true;
            else j = false;
        }
}

occurs an error saying that j is an rvalue so I can't bind lvalue reference to it. Why is it rvalue? If I'm getting it right, it's not an expression, but existing in memory element of vector i. What's more, it works just fine when I use only one loop.

I know that I can easily replace that with normal for loop, but I want to understand why that's wrong and learn if I can use nested c++11 for loop when I want to change values.

Lena
  • 31
  • 2
  • What is the purpose of the first loop? Why not simply do `vector> p(n, vector(m));`? I suggest [this `std::vector` reference](http://en.cppreference.com/w/cpp/container/vector), especially [the constructor reference](http://en.cppreference.com/w/cpp/container/vector/vector) (see overload 2). – Some programmer dude Nov 04 '17 at 19:56
  • As for your problem, use type-deduction with `auto` instead. – Some programmer dude Nov 04 '17 at 20:00

1 Answers1

2

std::vector<bool> is not a vector of bool instances. See the cppreference page for an explanation.

The issue here is that bool& j : i is trying to take every element of i by bool&. But i does not actually contain booleans - it will return some sort of proxy object that behaves like one.


This minimal example reproduces the issue:

std::vector<bool> i;
for(bool& j : i) { }  

on godbolt

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416