5

I need to complement the values of std::vector<bool>. So I thought of using range for loop taking elements by reference. But the compiler is giving me the below error

error: cannot bind non-const lvalue reference of type 'std::_Bit_reference&' to an rvalue of type 'std::_Bit_iterator::reference'
   13 |     for (auto& bit : rep)

This is my sample code

#include <iostream>
#include <vector>

int main() {
    std::vector<bool> rep;
    rep.push_back(true);
    rep.push_back(false);
    rep.push_back(true);
    rep.push_back(false);
    rep.push_back(true);
    rep.push_back(false);

    for (auto& bit : rep)
        bit = !bit;
}
Harry
  • 2,177
  • 1
  • 19
  • 33
  • This was probably a trick question, if you found it as challenge somewhere. – Sebastian Feb 06 '22 at 06:14
  • Does this answer your question? [Why does std::vector have no .data()?](https://stackoverflow.com/questions/46115669/why-does-stdvectorbool-have-no-data) – Sebastian Feb 06 '22 at 06:16
  • 1
    I would recommend to use `std::bitset` if possible. I think `std::vector` is design mistake that they have to keep. – Slava Feb 06 '22 at 06:38

2 Answers2

3

you can bind them (the returned proxy object) to rvalue reference

for (auto&& bit : rep)
   bit = !bit;

godbolt

apple apple
  • 10,292
  • 2
  • 16
  • 36
3

You could also use std::vector<bool>::flip to toggle every value in the vector<bool>.

std::vector<bool> rep{true, false, true, false, true, false};

for(bool v: rep)
    std::cout << v; 
std::cout << '\n';
rep.flip();
for(bool v: rep)
    std::cout << v;

Output:

101010
010101

std::vector<bool>::reference is the proxy type stored underneath which also has flip function std::vector<bool>::reference::flip.

for(auto&& v: rep)
    v.flip();
Ch3steR
  • 20,090
  • 4
  • 28
  • 58