I have a matrix of the form pMat[M][N]
(where M
and N
are variable and, hence, input from the user). I want to sort the elements of the 2-D array using the inbuilt std::sort
function.
For example, consider the following array:
5 9 6
8 1 3
7 2 4
It should be output as:
1 2 3
4 5 6
7 8 9
The following is the code that I wrote for the purpose:
#include <iostream>
#include <algorithm>
int main() {
int M, N, **pMat;
std::cin >> M >> N;
pMat = new int* [M];
for (int i=0; i<M; i++){
pMat[i] = new int[N];
}
for (int i=0; i<M; i++){
for (int j=0; j<N; j++){
std::cin >> pMat[i][j];
}
}
std::sort(&pMat[0][0], (&pMat[0][0])+(M*N));
for (int i=0; i<M; i++){
for (int j=0; j<N; j++){
std::cout << pMat[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
I wrote the above code based on the following understanding:
- Arrays in
C++
are stored in contiguous memory locations std::sort(add1,add2)
sorts all the elements present in the memory locations[add1,add2)
The above code doesn't give the correct output. For example, when provided with the following input:
4 3
13 2 1
4 5 6
7 8 9
10 11 12
it displays the following output:
0 0 0
5 6 13
7 8 9
10 11 12
How can I go about writing the code? And where is my understanding wrong?
(For information, I looked at the following answer: Sort a 2D array in C++ using built in functions(or any other method)? , but it does not answer my query)