bitmap的意义:将某些状态为 yes 或 no 等有意义的二值映射到最小内存单位bit上。对bit操作极大提升了运行效率,使用这种数据结构的优秀项目如:redis中的setbit
#include <iostream>
#include <stdexcept> /* std::out_of_range */
#include <bitset>
using namespace std;
const unsigned int BITMAP_SIZE = 100;
/* compile : g++ -std=c++11 bitset.cpp && time ./a.out */
int main(){
bitset<BITMAP_SIZE> m_bitset(std::string("10"));
/* 关键方法 */
cout << "full map :" << m_bitset << endl;
cout << "string of map :" << m_bitset.to_string() << endl;
cout << "counts of 1 :" << m_bitset.count() << endl;
cout << "counts of 0 :" << m_bitset.size() - m_bitset.count() << endl;
cout << "size of bitmap:" << m_bitset.size() << endl;
cout << "size of int :" << m_bitset.to_ulong() << endl;
cout << "any 1 in the map:" << m_bitset.none() << "(bool)" <<endl;
cout << "is all bit as 1:" << m_bitset.all() << "(bool)" << endl;
cout << "is any bit set:" << m_bitset.any() << "(bool)" <<endl;
cout << "full map :" << m_bitset << endl;
/* 修改 */
m_bitset[6] = "1";
m_bitset.set(6, 0);
m_bitset[6] = 1;
cout << "full map :" << m_bitset << endl;
/* 轮询 */
for(int i = 0; i < BITMAP_SIZE; i++)
{
try{
if (m_bitset.test(i))
cout << "index of " << i << " is :" << m_bitset[i] << endl;
} catch (const out_of_range& e){
cout << e.what() << endl;
}
}
/* 翻转 */
m_bitset.flip(0);
m_bitset.flip(1);
cout <<"full map flip :" << m_bitset << endl;
m_bitset.flip();
cout <<"full map flip :" << m_bitset << endl;
/* 重置 */
m_bitset.reset();
cout <<"full map reset:" << m_bitset << endl;
}