Harry
Harry

Reputation: 2971

how to complement the values of std::vector<bool> using range for loop taking element by reference

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;
}

Upvotes: 5

Views: 282

Answers (2)

Ch3steR
Ch3steR

Reputation: 20669

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();

Upvotes: 3

apple apple
apple apple

Reputation: 10591

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

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

godbolt

Upvotes: 3

Related Questions