zoukankan      html  css  js  c++  java
  • 按列存储的二维数组模版

     C/C++的多维数组是按行、连续存储的。

     任务:用类模板实现操作接口相同、按列存储的、任意
    元素类型的多维数组。

    #include <iostream>
    using namespace std;
    
    template<class T>
    class Array;
    
    template <class T>
    class ArrayTmp
    {
        friend class Array <T>;
        T* tpBody;
        int iRows,iColumns,iCurrentRow;
        ArrayTmp(int iRsz, int iCsz)
        {
            tpBody=new T[iRsz*iCsz];
            iRows=iRsz;
            iColumns=iCsz;
            iCurrentRow=-1;
        }
    public:
        T & operator[](int j)
        {
            return tpBody[iCurrentRow + (j*iRows)];
        }
        void diaplay1()
        {
            for (int i=0;i<iRows*iColumns;i++)
            {
                cout<<tpBody[i]<<" ";
            }
            
        }
    };
    
    template <class T>
    class Array
    {
        ArrayTmp<T> tTmp;
    public:
        ArrayTmp<T>& operator[](int i)
        {
            tTmp.iCurrentRow=i;
            return tTmp;
        }
        Array(int iRsz,int iCsz):tTmp(iRsz,iCsz){}
        void display2()
        {
            tTmp.diaplay1();
        }
    };
    
    void main()
    {
        Array<int> arr(2,3);
        arr[0][0]=1;
        arr[0][1]=2;
        arr[0][2]=3;
        arr[1][0]=4;
        arr[1][1]=5;
        arr[1][2]=6;
        cout<<arr[1][2]<<endl;
        arr.display2();
    
    }

    说明:1.程序中用了2个类型来进行下标i的传递。注意[]是但操作数的运算符。

             2.[]操作符即是取操作符也是存操作符。arr[0][0]=1存,cout<<arr[1][2];是取。

             3.若要实现按行存储的二维数组模版,程序相同,只是相应的i、j互换,此时两个类型间传递的是j.

             4.二维数组内部其实是按一维数组存储的,因按行、按列存储方式不同,对应的一维数组不同,如代码中的tpBody,所以通过display tpBody,便可以清晰的看出存储顺序来。

  • 相关阅读:
    docker镜像加速
    Job for network.service failed because the control process exited with error code
    python单例模式
    python实现简单算法
    Python母版使用
    Python中自定义filter用法
    linux挂载Windows共享文件夹
    重写用户模型时报错AttributeError: type object ‘自定义类’ has no attribute ‘USERNAME_FIELD’
    2020年3月10日 socket2
    2020年2月27日 socket 1
  • 原文地址:https://www.cnblogs.com/Yogurshine/p/2867853.html
Copyright © 2011-2022 走看看