位圖概念
所謂位圖,就是用每一位來存放某種狀態,適用於海量數據,數據無重複的場景。通常是用來判斷某個數據存不存在的
使用方式:
#include <iostream>
#include <bitset>
using namespace std;
int main() {
bitset<10> bt;
cout << bt << endl;
cout <<"size:"<< bt.size() << endl;
bt.set(4);
cout<<bt.set(3)<<endl; //設置某一位, 返回值是所操作的bitset對象
cout << bt.set(3, false) << endl; //將第三位設置爲0,set的第二個bool類型的參數默認值爲true
cout << bt.set() << endl; //設置所有位爲1
cout<<bt.test(3)<<endl; //測試某一位
cout << bt[3] << endl; //通過重載的運算符[]訪問某一位
//cout << bt[12] << endl; //越界操作程序會崩潰
//cout << bt.at(3)<<endl; //Vs2019將at方法刪除了,VS2013任然可以用
//cout << bt.at(12) << endl; //越界操作程序會崩潰
cout << bt.reset(3) << endl;
cout<<bt.reset()<<endl; //將所有位重置爲0
cout << bt.flip() << endl; //所有二進制位取反
cout << (bt <<= 2) << endl; //左移兩位
cout << bt.count() << endl; //統計位爲1的位數
cout << bt.to_ulong() << endl; //將位圖轉換爲unsigned long類型
cout << bt.to_ullong() << endl; //將位圖轉換爲unsigned long long類型
auto s = bt.to_string();
cout << typeid(s).name() << endl;
cout << bt.to_string() << endl; //將位圖轉換爲string類型
return 0;
}
bitset模擬實現
#include <iostream>
#include <vector>
using namespace std;
//simulation of bitset
template<size_t _N>
class bitSet {
public:
bitSet() :_bitArray((_N >> 5) + 1), _bitCount(_N) { //_N/32+1
}
void set(size_t pos) {
if (pos >= _bitCount)
return;
_bitArray[pos >> 5] |= (1 << (pos % 32));
}
#if 0
//C++11
size_t count() {
int bitCnttable[256] = {
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2,
3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3,
3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3,
4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4,
3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5,
6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4,
4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5,
6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5,
3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3,
4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6,
6, 7, 6, 7, 7, 8 };
size_t size = _bit.size();
size_t count = 0;
for (size_t i = 0; i < size; ++i)
{
int value = _bit[i];
int j = 0;
while (j < sizeof(_bit[0]))
{
unsigned char c = value;
count += bitCntTable[c];
++j;
value >>= 8;
}
}
return count;
}
#else
//vC6.0-C++98
size_t count() const {
int size = _bitArray.size();
size_t _V = 0;
for (int i = size - 1; 0 <= i; --i) {
for (size_t eachEle = _bitArray[i]; eachEle != 0; eachEle >>= 4)
_V += "\0\1\1\2\1\2\2\3\1\2\2\3\2\3\3\4"[eachEle & 0xF];
}
return _V;
}
#endif
private:
vector<int> _bitArray;
size_t _bitCount;
};
int main() {
bitSet<36> bs;
bs.set(10);
bs.set(20);
bs.set(30);
bs.set(35);
cout<< bs.count() << endl;
return 0;
}