std::bitset::all substitute for prior C++11 compilers

344 views Asked by At

I would like to use the std::bitset::all but unfortunately my compiler is pre-dated C++11. I know that I could mimicate the functionality by checking in a loop whether all bits of my std::bitset are set.

e.g.,

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 proper implementation of a std::bitset::all substitute for pre-dated C++11 compilers than the one displayed above.

5

There are 5 answers

2
101010 On

Another way would be to use template metaprogramming and unroll the bits of the bitfield like the example 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

4
Rapptz On

Just check if the count is equal to size:

template<size_t N>
bool all_set(const std::bitset<N>& b) {
    return b.count() == b.size();
}
1
Bulletmagnet On

A silly way would be

(~bs).none();

(silly because operator~ returns a temporary).

5
leemes On

If you want to avoid a loop, but don't care about maximum performace, you could compare count against size (i.e. check if the number of bits set equals the number of bits):

template<std::size_t N>
bool all(std::bitset<N> const &bs) {
    return bs.count() == bs.size();
}

The downside (but that's the same with other non-loop solutions as well as your implementation with a loop) is that it won't stop early at the first bit not being set. If you'd like to take advantage of that, modify your loop to exit early (and by the way, you don't need sz as 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;
}
0
Sebastian Redl On

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