Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

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

godbolt

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading