Created
May 13, 2014 14:32
-
-
Save id-0x76adf1/7718f9ad06c914c65550 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // bit_vector.h | |
| // | |
| // Created by identifer on 5/12/14. | |
| // Copyright (c) 2014 identifer. All rights reserved. | |
| // | |
| #ifndef BIT_VECTOR_H | |
| #define BIT_VECTOR_H | |
| #include <cstdint> | |
| #include <cstring> | |
| class bit_vector { | |
| public: | |
| static const uint32_t k_bits_per_byte = 8; | |
| static const uint32_t k_bits_per_uint32 = sizeof(uint32_t) * k_bits_per_byte; | |
| bit_vector() = default; | |
| explicit bit_vector(uint32_t capacity) { | |
| uint32_t remainder = capacity % k_bits_per_uint32; | |
| uints_num_ = capacity / k_bits_per_uint32; | |
| if (remainder != 0) { | |
| uints_num_ += 1; | |
| } | |
| bits_ = new uint32_t[uints_num_]; | |
| std::memset(bits_, 0, sizeof(uint32_t) * uints_num_); | |
| size_ = 0; | |
| } | |
| bit_vector(const bit_vector& that) { | |
| bits_ = new uint32_t[that.uints_num_]; | |
| std::memcpy(bits_, that.bits_, sizeof(uint32_t) * that.uints_num_); | |
| uints_num_ = that.uints_num_; | |
| size_ = that.size_; | |
| } | |
| bit_vector& operator=(const bit_vector& that) { | |
| if (&that == this) { | |
| return *this; | |
| } | |
| uint32_t* temp_bits = new uint32_t[that.uints_num_]; | |
| std::memcpy(temp_bits, that.bits_, sizeof(uint32_t) * that.uints_num_); | |
| delete [] bits_; | |
| bits_ = nullptr; | |
| uints_num_ = that.uints_num_; | |
| size_ = that.size_; | |
| return *this; | |
| } | |
| ~bit_vector() { | |
| if (bits_) { | |
| delete [] bits_; | |
| } | |
| uints_num_ = 0; | |
| size_ = 0; | |
| } | |
| void push_back(bool is_set); | |
| void push_back(uint32_t bits); | |
| void is_set(uint32_t index); | |
| uint32_t size() const { | |
| return size_; | |
| } | |
| uint32_t capacity() const { | |
| return uints_num_ * k_bits_per_uint32; | |
| } | |
| private: | |
| uint32_t* bits_ = nullptr; | |
| uint32_t uints_num_ = 0; | |
| uint32_t size_ = 0; | |
| }; | |
| #endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment