If you want to avoid a loop, but don't care about maximum performance, you can compare count
with size
(i.e. check if the number of bits is set to the number of bits):
template<std::size_t N> bool all(std::bitset<N> const &bs) { return bs.count() == bs.size(); }
The disadvantage (but the same with other non-loop solutions, as well as with your loop implementation) is that it will not stop early when the first bit is not set. If you want to take advantage of this, change your loop to exit earlier (and by the way, you don't need sz
since it is N
):
template<std::size_t N> bool all(std::bitset<N> const &bs) { for (int i = 0; i < N; ++i) if (!bs[i]) return false; return true; }
source share