sorting two dimensional arrays in C++ -


suppose have 2-d array a[4][2] this:

1 4 2 3 3 2 4 1 

i sort arrays in array in increasing order of second numbers, i.e. after sorting, array this:

4 1 3 2 2 3 1 4 

i thought of making map stores indices of numbers in second columns, , making array of numbers in second column , sorting array, reconstructing array new order of second column , map. problem, however, 2 numbers in second column might not distinct, if number appears twice, map[i] store last index. also, manually checking positions of first numbers corresponding second numbers take o(n^2) time. want in o(n log n). have suggestions? there built in method (c++ 4.3.2 / 4.8.1)?

thanks in advance.

you can std::sort. you'll need supply custom comparator thats not problem.

its easier if use std::array define 2 dimensional array though follows:

std::array< std::array< int, 2 >, 4 > twodarray; 

you can sort follows:

std::sort( twodarray.begin(), twodarray.end(), []( const std::array< int, 2 >& a, const std::array< int, 2 >& b ) {     return a[1] < b[1]; } 

doing same c-style array still possible require implementation of custom iterator advances whole "row" @ time standard iterator (ie pointer) treat 2d array if 1d.

here full example using c++ arrays:

std::array< std::array< int, 2 >, 4 > arr   = {{ { 1, 4 },                                                  { 2, 3 },                                                  { 3, 2 },                                                  { 4, 1 } }};  std::sort( arr.begin(), arr.end(), []( const std::array< int, 2 >& a, const std::array< int, 2 >& b )     {         return a[0] < b[0];     } );  std::sort( arr.begin(), arr.end(), []( const std::array< int, 2 >& a, const std::array< int, 2 >& b )     {         return a[1] < b[1];     } ); 

Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -