Check whether std::vector is comprised of on

2019-07-15 03:09发布

问题:

What is the fastest way to determine whether a vector holding boolean values (which is typically optimized as a bit array) only holds true values? For small vectors, I think it might not be a bad idea to just compare the vector against another vector storing only true values (assuming we know the size of both vectors).

回答1:

Given const vector<bool> foo(13) use find:

cout << (find(foo.begin(), foo.end(), false) == foo.end()) << endl;

Or if you have c++11 you can none_of:

cout << none_of(cbegin(foo), cend(foo), logical_not<bool>()) << endl;

Alternatively if you know your vector's size at compile time you can use bitset'a all method:

bitset<13> foo;

cout << foo.all() << endl;

Live Examples