Reputation: 91
For example:
b = [T T F F T F], then the function return 3 .
I can do that by a for-loop program. But, is there function return " the number of true value in a boolean vector " to do that faster than for-loop program ?
Thanks.
Upvotes: 3
Views: 9874
Reputation: 3908
Just for completeness, we can also use std::reduce
, setting the initial value to 0
:
#include <iostream>
#include <vector>
#include <numeric> // for std::reduce
int main() {
std::vector<bool> vb{ true, false, true, true, };
std::cout << std::reduce(vb.cbegin(), vb.cend(), 0); // Set the init value to 0.
return 0;
}
Without setting the initial value, the return value would be true
if at least one true
exists.
Upvotes: 0
Reputation: 1993
std::count(b.begin(), b.end(), true);
Might be a good idea. More detailed if you want to try:
#include <vector> // std::vector
#include <algorithm> // std::count
#include <iostream> // std::cout, std::endl
int main(){
std::vector<bool> b = { true, true, false, true, false, true };
auto count = std::count(b.begin(), b.end(), true);
std::cout << "Count = " << count << std::endl;
return 0;
}
Count = 4
Upvotes: 17
Reputation: 16089
The space saving implementation of std::vector<bool>
is ... implementation defined, so there is no portable way of doing it.
But if you really really need to be fast here and don't mind rewriting your program each time a new patch/version of your compiler, cpu, OS comes out, there is a way for most implementation.
Most implementations will probably implement it as an array of some type of int, if you can get access to that array you can use your cpu's popcount/simd instructions to count it in potentially O(n/m) instead of O(n), where m is the max wordlength that can be popcounted on your cpu.
Evil minds will postulate that O(n/m) is O(n) but that speed up can be significant.
Edit: I forgot there is another possibility, namely std::bitset if you don't really need a vector of bool. std::bitset has a count, but again its implementation defined how count is done.
Upvotes: -1