dl
dl_vector_bit.h
浏览该文件的文档.
1
14#pragma once
15
16#include <vector>
17#include <cassert>
18#include <bitset>
19
20namespace dl
21{
24 {
25 using Byte = unsigned char;
26 public:
27 // 二进制数据
28 void* GetData()
29 {
30 return _data.data();
31 }
32 size_t GetDataSize()
33 {
34 return _data.size();
35 }
36
37 // 容器意义
38 void SetBit(size_t index, bool v)
39 {
40 size_t j = index / 8;
41 size_t i = index % 8;
42
43 _set(j, i, v);
44 }
45 bool GetBit(size_t index)
46 {
47 size_t j = index / 8;
48 size_t i = index % 8;
49
50 return (_data[j] >> i) & 1;
51 }
52
53 size_t size() const
54 {
55 return _data.size() * 8 + _i;
56 }
57 void resize(size_t n, bool v)
58 {
59 // 旧
60 size_t j_old = _data.size();
61 if (j_old > 0)
62 --j_old;
63 // 新位置
64 size_t j = n / 8;
65
66 _data.resize(j + 1, v);
67
68 if (j < j_old)
69 {// 块容量缩小
70 ;
71 }
72 else if (j > j_old)
73 {// 块容量扩大,旧的最后一块 (i_old, 8) 填充新值
74 for (size_t k = _i + 1; k < 8; ++k)
75 _set(j_old, k, v);
76 }
77 else
78 {// 块容量相等,旧的最后一块 从 (i_old, i] 填充新值
79 size_t i = n % 8;
80 for (size_t k = _i + 1; k < i; ++k)
81 _set(j_old, k, v);
82 }
83 }
84 // 注意 _i 的正确性
85 void assign(void* p, size_t n)
86 {
87 _data.resize(n);
88 memcpy(_data.data(), p, n);
89 }
90 VectorBit() :_i{ 0 }
91 {
92 }
93 private:
94 std::vector<unsigned char> _data; // size 为 j
95 size_t _i;
96
97 void _set(size_t j, size_t i, bool v)
98 {
99 assert(i < 8);
100 if (v)
101 _data[j] |= (1 << i);
102 else
103 _data[j] &= ~(1 << i);
104 // 反转 number ^ ((Uint)1 << n);
105 }
106 };
107
108
109}
110
111// 可参考boost的代码进一步优化
112//resize(size_type num_bits, bool value) // strong guarantee
113//{
114// const size_type old_num_blocks = num_blocks();
115// const size_type required_blocks = calc_num_blocks(num_bits);
116//
117//
118// const block_type v = value ? Block(-1) : Block(0);
119//
120//
121// if (required_blocks != old_num_blocks) {
122// m_bits.resize(required_blocks, v); // s.g. (copy)
123// }
124//
125//
126// // At this point:
127// //
128// // - if the buffer was shrunk, we have nothing more to do,
129// // except a call to m_zero_unused_bits()
130// //
131// // - if it was enlarged, all the (used) bits in the new blocks have
132// // the correct value, but we have not yet touched those bits, if
133// // any, that were 'unused bits' before enlarging: if value == true,
134// // they must be set.
135//
136//
137// if (value && (num_bits > m_num_bits)) {
138// const int extra_bits = count_extra_bits();
139// if (extra_bits) {
140// BOOST_ASSERT(old_num_blocks >= 1 && old_num_blocks <= m_bits.size());
141//
142//
143// // Set them.
144// m_bits[old_num_blocks - 1] |= (v << extra_bits);
145// }
146// }
147//
148//
149// m_num_bits = num_bits;
150// m_zero_unused_bits();
151//}
void assign(void *p, size_t n)
bool GetBit(size_t index)
void SetBit(size_t index, bool v)
void resize(size_t n, bool v)
size_t size() const