how to create a contiguous 2d array in c++?

后端 未结 7 1502
走了就别回头了
走了就别回头了 2020-11-21 23:52

I want to create a function that returns a contiguous 2D array in C++.

It is not a problem to create the array using the command:

 int (*v)[cols] = n         


        
7条回答
  •  再見小時候
    2020-11-22 00:31

    I think you should write a simple class to wrap a 1-dim array. Then you can implement a 2-dim array with operator() overloading for getting values and deconstruct func for release the memory. Code as below:

    #include 
    
    template 
    class Array_2D
    {
    private:
        T *data_inside;
    public:
        int size[2];
        Array_2D(int row, int column);
        ~Array_2D();
    
        // 
        T operator()(int index1, int index2){
            return data_inside[get_index(index1, index2)];
        }
    
        int get_index(int index1, int index2){
            if(index1>=0 and index1=0 and index2<=size[1]){
                return index1*size[0] + index2;
            }else{
                assert("wrong index for array!" == "True");
            }
        }
    
    };
    
    template 
    Array_2D::Array_2D(int row, int column)
    {
        size[0] = row;
        size[1] = column;
        data_inside = new T[row*column];
    }
    
    template 
    Array_2D::~Array_2D()
    {
        // 使用析构函数,自动释放资源
        delete[] data_inside;
    }
    
    

提交回复
热议问题