Reputation: 1569
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).
P.S.: I know that std::vector is a broken thing, but it should suffice.
Upvotes: 1
Views: 1803
Reputation: 19757
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;
Upvotes: 4