zoukankan      html  css  js  c++  java
  • 通过bitmap的方式用8个int实现对256个char是否出现过做记录

    程序设计中经常会出现这样的场景:遍历一个字符串a(例如:“A dog in on the floor.”),对于字符串b(例如“dnr”)中出现过的字符,统统删掉。

    那么对于b中出现的字符,通常可以保存在bool label[256]中来记录某个字符是否在字符串b中。

    但是还可以用一种更省内存的方式,就是bitmap。

    通过定义Set,ReSet和Get宏来快速定位某一个bit。

    并且使用sizeof(int)和动态数组来适应64位平台。

    #include <iostream>
    using namespace std;
    
    int intWidth = sizeof(int) * 8;
    int *label = new int[256/intWidth];
    
    #define Set(i) label[i/intWidth] |= 1<<(i%intWidth)
    #define ReSet(i) label[i/intWidth] &= 0<<(i%intWidth)
    #define Get(i) (label[i/intWidth] >> (i%intWidth))&0x01
    
    int main()
    {
        memset(label, 0, 256/intWidth * sizeof(int));
        for (int i = 0; i < 256; i++)
        {
            unsigned char c = i;
            cout<<"====================================="<<endl;
            cout<<"i = "<<i<<"    c = "<<c<<endl;
            Set(c);
            cout<<"After Set("<<c<<") ";
            if (Get(c))
                cout<<c<<" exists!"<<endl;
            else
                cout<<c<<" not exists!"<<endl;
    
            ReSet(c);
            cout<<"After ReSet("<<c<<") ";
            if (Get(c))
                cout<<c<<" exists!"<<endl;
            else
                cout<<c<<" not exists!"<<endl;
            cout<<"====================================="<<endl<<endl;
        }
    
        return 0;
    }

    EOF

  • 相关阅读:
    面向消息的持久通信与面向流的通信
    通信协议
    分布式系统简介
    Hadoop on Yarn 各组件详细原理
    Parquet文件结构笔记
    Redis部分数据结构方法小结
    Storm Ack框架笔记
    MapReduce格式与类型
    Hadoop 2.6 MapReduce运行原理详解
    Hadoop SequenceFile数据结构介绍及读写
  • 原文地址:https://www.cnblogs.com/lihaozy/p/2816312.html
Copyright © 2011-2022 走看看