Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 944
101010 Avatar asked Nov 13 '14 13:11

101010


5 Answers

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();
}
like image 171
Rapptz Avatar answered Oct 10 '22 10:10

Rapptz


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;
}
like image 36
leemes Avatar answered Oct 10 '22 09:10

leemes


A silly way would be

(~bs).none();

(silly because operator~ returns a temporary).

like image 26
Bulletmagnet Avatar answered Oct 10 '22 11:10

Bulletmagnet


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

like image 24
Sebastian Redl Avatar answered Oct 10 '22 09:10

Sebastian Redl


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

like image 1
101010 Avatar answered Oct 10 '22 11:10

101010