C++二维比特数组

2021-02-06 23:16

阅读:365

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

#include 
#include 
#include 
#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  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 )
        {
            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 " ";
        }
        std::cout  std::endl;
    }
    std::cout 1,2)  std::endl;
}

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

C++二维比特数组

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

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


评论


亲,登录后才可以留言!