Std :: bitset :: all replace previous C ++ 11 compilers

I would like to use std::bitset::all , but unfortunately my compiler is pre-configured in C ++ 11. I know that I could simulate functionality by checking in a loop if all the bits of my std::bitset .

eg.

 template<std::size_t N> bool all(std::bitset<N> const &bs) { int hits(0), sz(bs.size()); for(int i(0); i < sz; ++i) { hits += bs[i]; } return hits == sz; } 

Q

Is there a more correct implementation of the std::bitset::all replacement for ready-made C ++ 11 compilers than the previous one.

+6
source share
5 answers

Just check if the count size matches:

 template<size_t N> bool all_set(const std::bitset<N>& b) { return b.count() == b.size(); } 
+7
source

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; } 
+5
source

Silly way would be

 (~bs).none(); 

(stupid because operator~ returns temporary).

+2
source

You can use bs.count() == bs.size() .

+2
source

Another way would be to use template metaprogramming and expand the bits of the bit field, as shown below:

 template<std::size_t N, int M> struct bitset_all_helper { static bool check(std::bitset<N> const &bs) { return bs[M] && bitset_all_helper<N, M - 1>::check(bs); } }; template<std::size_t N> struct bitset_all_helper<N, 0> { static bool check(std::bitset<N> const &bs) { return bs[0]; } }; template<std::size_t N> bool bitset_all(std::bitset<N> const &bs) { return bitset_all_helper<N, N - 1>::check(bs); } 

Live demo

+1
source

Source: https://habr.com/ru/post/978135/


All Articles