Why does this code work
std::vector intVector(10);
for(auto& i : intVector)
std::cout << i;
And this doesn\'t?
<
std::vector does not obey the standard container rules.
In particular, its operator[] does not return bool&.
The loop in the invalid code
#include
#include
int main() {
std::vector boolVector(10);
for (auto& i: boolVector)
std::cout << i;
}
can be rewritten in any of three ways to iterate through the values:
(read-only)
for (auto i: boolVector)
std::cout << i;
(read-only, possibly inefficient)
for (auto const& i: boolVector)
std::cout << i;
(read/write)
for (auto&& i: boolVector)
std::cout << i;
The choice between the first and last is down to whether you need to modify the values in the vector, or just to read them.