There's more...

The std::vector<bool> interface is very different from std::bitset. If you want to be able to write code in a similar manner, you can create a wrapper on std::vector<bool>, which looks like std::bitset, where possible. The following implementation provides members similar to what is available in std::bitset:

    class bitvector
{
std::vector<bool> bv;
public:
bitvector(std::vector<bool> const & bv) : bv(bv) {}
bool operator[](size_t const i) { return bv[i]; }

inline bool any() const {
for (auto b : bv) if (b) return true;
return false;
}

inline bool all() const {
for (auto b : bv) if (!b) return false;
return true;
}

inline bool none() const { return !any(); }

inline size_t count() const {
return std::count(bv.cbegin(), bv.cend(), true);
}

inline size_t size() const { return bv.size(); }

inline bitvector & add(bool const value) {
bv.push_back(value);
return *this;
}

inline bitvector & remove(size_t const index) {
if (index >= bv.size())
throw std::out_of_range("Index out of range");
bv.erase(bv.begin() + index);
return *this;
}

inline bitvector & set(bool const value = true) {
for (size_t i = 0; i < bv.size(); ++i)
bv[i] = value;
return *this;
}

inline bitvector& set(size_t const index, bool const value = true) {
if (index >= bv.size())
throw std::out_of_range("Index out of range");
bv[index] = value;
return *this;
}

inline bitvector & reset() {
for (size_t i = 0; i < bv.size(); ++i) bv[i] = false;
return *this;
}

inline bitvector & reset(size_t const index) {
if (index >= bv.size())
throw std::out_of_range("Index out of range");
bv[index] = false;
return *this;
}

inline bitvector & flip() {
bv.flip();
return *this;
}

std::vector<bool>& data() { return bv; }
};

This is only a basic implementation, and if you want to use such a wrapper, you should add additional methods, such as bit logic operations, shifting, maybe reading and writing from and to streams, and so on. However, with the preceding code, we can write the following examples:

    bitvector bv;
bv.add(true).add(true).add(false); // [1, 1, 0]
bv.add(false); // [1, 1, 0, 0]
bv.add(true); // [1, 1, 0, 0, 1]

if (bv.any()) std::cout << "has some 1s" << std::endl;
if (bv.all()) std::cout << "has only 1s" << std::endl;
if (bv.none()) std::cout << "has no 1s" << std::endl;
std::cout << "has " << bv.count() << " 1s" << std::endl;

bv.set(2, true); // [1, 1, 1, 0, 1]
bv.set(); // [1, 1, 1, 1, 1]

bv.reset(0); // [0, 1, 1, 1, 1]
bv.reset(); // [0, 0, 0, 0, 0]

bv.flip(); // [1, 1, 1, 1, 1]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset