Jump to content
  • Advertisement
Sign in to follow this  

Sorting 2D array

This topic is 2807 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

The problem:
Order the lines of array according to growth of the characteristic of a line. Consider the characteristic of a line - the sum of its positive even elements.

How do i swap the rows between them ?

Share this post

Link to post
Share on other sites
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.


// 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
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!