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

  • 相关阅读:
    【持续更新】Android 源码下载地点
    android Notification 的使用
    如何设置 Notification 中PendingIntent 的 Intent
    CodeSmith部分类型转换代码
    【转】Request.ServerVariables参考
    ADT
    根据IP从纯真IP数据库查询地址
    VS2008重置默认环境
    Eclipse 安装SVN插件
    C#序列化JSON对象
  • 原文地址:https://www.cnblogs.com/lihaozy/p/2816312.html
Copyright © 2011-2022 走看看