I define the square matrix by a 2D dynamic array with the new operator following:
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));
Then I have tried to print that array out by operator << 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;
}
Please help me to make it work! I could solved that as the function void printing2DArray(…), but just want to do that with operator << overloading. Thank you.
8
You’d normally do this by creating a class to hold your 2-D matrix, then overloading operator<<
for instances of that class:
template <class T>
class matrix2d {
std::vector<T> data;
std::size_t cols;
std::size_t rows;
public:
matrix2d(std::size_t y, std::size_t x) : cols(x), rows(y), data(x*y) {}
T &operator()(std::size_t y, std::size_t x) {
assert(x<=cols);
assert(y<=rows);
return data[y*cols+x];
}
T operator()(std::size_t y, std::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;
}
};
live on Godbolt
5