Sign in to follow this  
LastSamuray

Sorting 2D array

Recommended Posts

Treat each row of the 2D array as a separate object.

In C++, the easiest way to do this is to use boost::array as a replacement for built-in arrays. Each boost::array represents a 1-D array, but you can nest them.

Thus:


// Of course you will have to download Boost and set it up, and #include
// the appropriate headers.

// Let us use typedefs to make it more clear what is going on.
typedef boost::array<int, COLUMNS> row;
typedef boost::array<row, ROWS> array;

// We define the "characteristic":
int characteristic(const row& r) {
// We can index into a boost::array the same way as a normal array.
// So, it should not be hard for you to write this. :)
}

// We need a comparison function to supply to the standard library sort:
bool compare_by_characteristic(const row& a, const row& b) {
return characteristic(a) < characteristic(b);
}

// And use the standard library to sort:
row* begin = &array[0];
std::sort(begin, begin + ROWS, compare_by_characteristic);

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this