I need an implementation of the minimum size of a bools array. The size of the array is known at compile time.
I checked std::bitsetand boost::array, but they both carry overhead, which is important for small arrays. For example, if the size of the array is 8 , the container should use only 1 byte of memory (provided that the overall CPU architecture is used).
Is it there, or do I need to roll my own?
EDIT : Here is my final implementation based on Tom Kenapen's post. I added a default value for the constructor and added metalization in the case of an index outside the bounds. Many thanks to Tom and everyone else.
#include <stdexcept>
#include <climits>
template<int SIZE>
class bitarray
{
public:
bitarray(bool initial_value = false);
bool get(int index) const;
void set(int index, bool value);
private:
static const int ARRAY_SIZE = (SIZE + CHAR_BIT - 1) / 8;
unsigned char mBits[ARRAY_SIZE];
};
template<int SIZE>
inline bitarray<SIZE>::bitarray(bool initial_value)
{
for(int i = 0; i < ARRAY_SIZE; ++i)
mBits[i] = initial_value ? -1 : 0;
}
template<int SIZE>
inline bool bitarray<SIZE>::get(int index) const
{
if (index >= SIZE)
throw std::out_of_range("index out of range");
return (mBits[index / CHAR_BIT] & (1 << (index % CHAR_BIT)));
}
template<int SIZE>
inline void bitarray<SIZE>::set(int index, bool value)
{
if (index >= SIZE)
throw std::out_of_range("index out of range");
if (value)
mBits[index / CHAR_BIT] |= (1 << (index % CHAR_BIT));
else
mBits[index / CHAR_BIT] &= ~(1 << (index % CHAR_BIT));
}
source
share