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.
newinstead ofstd::vector? It is recommended anyway, and will also make overloadingoperator<<easier.Matrixand work with it. Don't pepper your code with raw pointers. YourpMatrixisint*notint* [something]. You cannot recover the number of elements from a raw pointer.if(pMatrix == NULL)is useless here sincepMatrixcan never be null here. Will new operator return NULL? and Why doesn't new in C++ return NULL on failureendlandusing namespace std;. I would also expext that you would make a Matrix class and then useostream& operator<< (ostream &os, const Matrix<customizedType>&. A pointer is NOT a matrix