C++ 之 #include <bitset>

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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值