简体   繁体   中英

std::vector<bool> with only one true element

I need an std::vector<bool> , in which only one element may be true later in the program. My attempt was ( in a for-loop)

BOOST_FOREACH( bool b, boolvector)
{
    b = false;
}
boolvector[j] = true;

But when this executes the elements don't get reset to false when doing the BOOST_FOREACH (function of the boost library to iterate more conveniently through containers ( see boost documentation ).

PS: I know that std::vector is a broken thing, but it should suffice.

I will try this in a few minutes, but I suspect you want

BOOST_FOREACH(std::vector<bool>::reference b, boolvector)
{
    b = false;
}

std::vector<bool> , as you say, is "broken", and dereferencing an iterator doesn't give you a nice convenient reference, it gives you some proxy object: http://en.cppreference.com/w/cpp/container/vector_bool

Edit: Yes, this works:

#include <algorithm>
#include <iomanip>
#include <iostream>
#include <vector>

#include <boost/foreach.hpp>

void print (const std::vector<bool>& bv)
{
    std::cout << std::boolalpha;
    for (auto it = std::begin(bv); it != std::end(bv); ++it)
        std::cout << *it << ' ';
    std::cout << '\n';
}


int main()
{
    std::vector<bool> boolvector {true, false, true, false};
    print(boolvector);

    BOOST_FOREACH(std::vector<bool>::reference b, boolvector)
    {
        b = false;
    }

    print(boolvector);
}

Prints:

$ ./a.out 
true false true false 
false false false false 

This:

BOOST_FOREACH(auto b, boolvector)

also works, but

BOOST_FOREACH(auto& b, boolvector)

does not (fails to compile due to non- const reference to temporary).

However, as Nawaz points out, if you have c++11 support, just ditch BOOST_FOREACH entirely, and write:

for (auto b : boolvector)

Much later edit:

I don't know how I missed this in the first place, but it looks like the correct solution here is to use assign :

b.assign(b.size(), false);
b[i] = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM