C++ 运算符 << overloading for a 2D dynamic array allocation

问题描述 投票:0回答:1

我通过二维动态数组定义方阵,并使用以下新运算符:

int n, i{0};
    int value;

    do {
        cin >> n;
    } while ((n <=0) || (n > 20));

    int* pMatrix = new int [n*n];
    if(pMatrix == NULL) return 1;

    do {
        cin >> value;
        *(pMatrix + i) = value;
        i++;
    } while (i < (n*n));

然后我尝试通过运算符打印该数组<< overloading, following:

template <typename customizedType, int matrixEdge>
ostream& operator<< (ostream &os, const customizedType* inputMatrix[matrixEdge]) {
    os << "{ ";
    for (int i = 0, matrixSize = matrixEdge*matrixEdge; i < matrixSize; i++) {
        os << *(inputMatrix + i) << ' ';
        if (((i+1) % matrixEdge) == 0 && (i < matrixSize-1)) {os << '}' << endl; os << "{ ";}
    }
    os << '}' << endl;
    return os;
}

请帮助我让它发挥作用!我可以用 void print2DArray(...) 函数解决这个问题,但只想用运算符 << overloading. Thank you.

来解决这个问题
c++ multidimensional-array operator-overloading dynamic-memory-allocation
1个回答
0
投票

通常,您可以通过创建一个类来保存二维矩阵,然后为该类的实例重载

operator<<
来实现此目的:

template <class T>
class matrix2d {
    std::vector<T> data;
    std::size_t cols;
    std::size_t rows;
public:
    matrix2d(size_t y, size_t x) : cols(x), rows(y), data(x*y) {}
    T &operator()(size_t y, size_t x) { 
        assert(x<=cols);
        assert(y<=rows);
        return data[y*cols+x];
    }
    T operator()(size_t y, size_t x) const { 
        assert(x<=cols);
        assert(y<=rows);
        return data[y*cols+x];
    }

    friend std::ostream &operator<<(std::ostream &os, matrix2d const &m) {
        for (std::size_t y=0; y<m.rows; y++) {
            for (std::size_t x = 0; x<m.cols; x++) {
                os << m(y,x) << "\t";
            }
            os << "\n";
        }
        return os;
    }
};

在 Godbolt 上直播

© www.soinside.com 2019 - 2024. All rights reserved.