Re: Bool vector reference
* juraj:
Erik Wikstr?m <Erik-wikstrom@telia.com> wrote in message
<news:AMxyj.4319$R_4.3142@newsb.telia.net> on 2.3.2008 14:16 GMT+1 in
comp.lang.c++:
You mean you are trying to pass an element from vector<bool> to a
function that takes a reference to a bool?
Yes. Exactly.
It seems you have been bitten by the fact that vector<bool> is a specialisation
and the values returned from operator[] and at() are not bools, but rather a
wrapper around a value. Change the function to take a bool and not a reference.
Actually, I was passing two bools, and I needed them both modified outside
the function.
As I said, I got the following example with pointers to work, although the
compiler issued a warning ("taking address of temporary"), and I feel it's
unsafe because of that. Is this dangerous to do?
Yes.
#include <vector>
using namespace std;
void myboolOR(boolpointer *first, boolpointer *second){
if(*first || *second) *first=*second=true; }
This will not compile.
It's a good idea to post actual code.
int main() {
vector<bool> myVector(4, 0); // 0000
myVector[1]=true; // 0100
myboolOR(&myVector[1], &myVector[2]); // 0110
}
The only other thing on my mind is to declare two temporary bools in the
main function, assign the values from the bools vector to them, call the
function on them, and assign their values back to the bools in vector.
However, this way I can end up with even messier code than the one I've
tried to simplify by writing the function.
You can do e.g.
<code>
#include <vector>
// I/O:
#include <iostream>
#include <ostream>
#include <iterator>
#include <algorithm>
typedef std::vector<bool>::reference BoolRef;
void myboolOR( BoolRef first, BoolRef second)
{
if( first || second ) { first = second = true; }
}
int main()
{
using namespace std;
vector<bool> myVector( 4 ); // 0000
myVector[1] = true; // 0100
myboolOR( myVector[1], myVector[2] ); // 0110
copy(
myVector.begin(), myVector.end(),
ostream_iterator<bool>( cout )
);
cout << endl;
}
</code>
std::vector<bool>::reference also has a handy flip() member function.
However, the whole std::vector<bool> class is just an example of the
evils of premature optimization.
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?