Sorting 2D Array C++

1110101001

Is it possible to sort a 2D Array using qsort or std::sort in C++ such that the elements are in increasing order when read from left to right in each row or from top to bottom in each column?

For example,

13, 14, 15, 16
1, 4, 3, 2
7, 5, 7, 6
9, 10, 11, 12

Becomes:

{ 1, 2, 3, 4 }
{ 5, 6, 7, 8 }
{ 9, 10, 11, 12 }
{ 13, 14, 15, 16 } 

I know you can do it by creating two comparison functions and then first sorting each row then comparing the first elements of each row to establish the columns, but is there a way to do it in one function itself?

4pie0

Yes. C++ STL library is built with separation of algorithms and containers. What links them together is iterators. Raw pointer is iterator, therefore it is possible to initialize vector with raw pointers and then sort that vector as usual.

std::vector<int> v(arr2d, arr2d + N); // create a vector based on pointers
                                      // This assumes array is contiguous range 
                                      // in memory, N=number of elemnts in arr2d
// using default comparison (operator <):
std::sort (v.begin(), v.end());

// cout by 4 elements in a row

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related