1

Why does iterating over a vector of bool ( w/ modifying the element) require the &&, and not the vector of int?

// junk10.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <algorithm>
#include <array>
#include <vector>

using namespace std;

int main()
{   
    vector<int> miv{ 1, 2, 3 };
    for (auto &e : miv) { e = 15; } // Legal
    vector<bool> mbv{ false };
    for (auto &e : mbv) { e = true; } // Illegal
    for (auto &&e : mbv) { e = true; } // Legal

    return 0;
}
  • Because [`std::vector`](http://en.cppreference.com/w/cpp/container/vector_bool) is not a vector like any other. – Some programmer dude May 08 '18 at 02:58
  • Thank you, that post mostly explains the reason. By mostly, I mean I mostly understand the explanation; the post you linked to is almost certainly 100% accurate and complete. – user3772662 May 08 '18 at 03:24

1 Answers1

0

The way std::vector<bool> is implemented, is that for space efficiency each boolean occupies 1 bit and not 1 byte, as a boolean.

This means you cannot take a reference to it. A reference is a wrapped pointer, and you cannot have a pointer to a bit.

You can use auto && in C++ 11 to modify the bit, but note that auto does not become a boolean:

std::vector<bool> vec { 1, 0, 1 };
bool &&i = vec[1];
i = 1;              // DOES NOT MODIFY VECTOR
auto &&k = vec[2];
k = 0;              // MODIFIES VECTOR

for (bool i : vec)  
    std::cout << i;

100

Kostas
  • 4,061
  • 1
  • 14
  • 32