Here’s an easy way for sorting a 2D array according to one of its columns while keeping each of the rows together. This implementation uses STL vectors.
#include <vector> #include <algorithm> #include <cstdlib> #include <ctime> using namespace std; // This makes the sort be according to column 2 and ascending bool sortFunc( const vector<int>& p1, const vector<int>& p2 ) { return p1[1] < p2[1]; } int main() { srand(time(NULL)); // Creates and initializes 10 x 4 vector vector< vector<int> > vec; for( int i=0; i<10; i++ ) { vector<int> tmpVec; for( int j=0; j<2; j++ ) { tmpVec.push_back( rand()%10 ); } vec.push_back( tmpVec ); } // Print out the pre-sorted vector cout << "Pre-sorting state:" << endl; for( int i=0; i<vec.size(); i++ ) { for( int j=0; j<vec[i].size(); j++ ) { cout << vec[i][j] << " "; } cout << endl; } cout << endl; // Do the sorting according to column 2 sort(vec.begin(), vec.end(), sortFunc); // Print out the post-sorted vector cout << "Post-sorting state:" << endl; for( int i=0; i<vec.size(); i++ ) { for( int j=0; j<vec[i].size(); j++ ) { cout << vec[i][j] << " "; } cout << endl; } return 0; }
The key function here is sort() on line 38. Its third argument is the function sortFunc() which compares the second column element of each row and returns TRUE if the order is correct.
thank you! very helpful
Thanks so much this is very useful
Clearest example I have seen of this useful technique. BFP