# Sorting 2D array

## 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 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.

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);

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628348
• Total Posts
2982208

• 10
• 9
• 24
• 11
• 9