码迷,mamicode.com
首页 > 编程语言 > 详细

C++二维比特数组

时间:2020-04-26 17:21:35      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:string   ==   har   lse   比特   unsigned   val   c++   pre   

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;

class BitArray2D
{
private:
    int mRow, mCol;
    unsigned char **A, *B;
    bool isValid(int row, int col)
    {
        return row > 0 && col > 0 && row <= mRow && col <= mCol;
    }
    
public:
    BitArray2D(const int &row, const int &col) : mRow(row), mCol(col)
    {
        if(!isValid(row, col))
            std::cerr << "parameter error." << std::endl;

        int i, j;
        int r = row;
        int c = (col%8 == 0) ? col/8 : col/8 + 1;
        
        A = new unsigned char *[r]();
        B = new unsigned char[r*c]();

        for(i=0,j=0; i < r; i++)
        {
            A[i] = &B[j];
            j += c;
        }
    }

    ~BitArray2D()
    {
        delete B;
        delete []A;
    }

    bool bitGet(int row, int col)
    {
        if(!isValid(row, col))
            return false;
        return A[row][col >> 1] & (1 << col);
    }
    
    void setOne(int row, int col)
    {
        if(!isValid(row, col))
            return;
        A[row][col >> 1] |= (1 << col);
    }

    void setZero(int row, int col)
    {
        if(!isValid(row, col))
            return;
        A[row][col >> 1] &= ~(1 << col);
    }
};


int main()
{
    BitArray2D ba(3,4);
    ba.setOne(1,2);
    int i,j;
    for(i = 0; i < 3; i++)
    {
        for(j = 0; j < 4; j++)
        {
            std::cout << ba.bitGet(i,j) << " ";
        }
        std::cout << std::endl;
    }
    std::cout << ba.bitGet(1,2) << std::endl;
}

 想尽各种办法实现[][]的重载都失败了。只好用()替代。使用起来也还行。

C++二维比特数组

标签:string   ==   har   lse   比特   unsigned   val   c++   pre   

原文地址:https://www.cnblogs.com/abnk/p/12780507.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!