How to track when all the elements of a vector <bools> are false?

Note: I'm not using c++ 11 unfortunately so I don't have access to all_of().

I basically have a vector <bool> isHovered;

As the name instantiates, when an element in particular on the screen gets hovered, a boolean assigned to it turns on and the others remain false. Because is a mouse interaction, only one element would be true at the time.

One thought that I had was to create a counter that increases every time a boolean becomes true. The problem with this approach is that because I have my for loop in an update function it checks all the time. Therefore, the counter will increase more than once while I'm hovering.

Now the question here is: is there any way to know by looping through the vector when all of the elements are false:

something like:

1
2
3
4
5
6
7
8
9
10

vector<bool>::iterator c;
for ( c = isHovered.begin(); c != isHovered.end(); c++ ){
 
 if( all of the elements are false){

   //do something
 }

}


Thanks in advance
This works beautifully, thanks so much. I came up with this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

vector<bool>::iterator d;
    
    d = find(isHovered.begin(), isHovered.end(), true);
    
    
    if ( d != isHovered.end()){
        
        cout << "One element is true" << *d << endl;
    }else{
        
        cout << "All of the elements are false" << endl;
    }
Last edited on
If the size of the vector doesn't change after it's constructed then you could use bitset instead. bitset has an any() method that is probably much faster.
http://www.cplusplus.com/reference/bitset/bitset/any/
@dhayden Thanks for you reply. Could you elaborate an example using bitset? I looked at the documentation reference, but I'm having a hard time trying to understand it. Thanks!
1
2
3
4
5
6
7
8
9
10
11
12
13
std::bitset<200> bits;   // create a set of 100 bits.
...
if (!bits.any()) {
   // do something if all bits are false. Ths is what you want..
} else if (bits.all(){ 
   // do something if all bits are true
}

bits[3] = true
bits.set(3, false);
if (bits.test(19)) 
    cout << bit 19 is true.
}

Topic archived. No new replies allowed.