简体   繁体   中英

Multi-Dimensional Array sorting in c++

I am using sort() function for single array it works well.
I also used this for multi-dimensional array but this is not work.
Here is code:

#include <iostream>


 using namespace std;

  int main(){

  int a[2][3];

    a[0][1]=7;
    a[1][0]=1;
    a[1][1]=3;

    sort(a,a+3);

    cout<<a[0][1]<<"\t"<<a[1][0]<<"\t"<<a[1][1];


return 0;
}

I know I use single array for these value but this is example and I want it in multi-dimensional array.

Using your code just use std::sort on each row of the multidimensional array. ie.

#include <iostream>


using namespace std;

int main(){

  int a[2][3];

  a[0][0]=1;
  a[0][1]=7;
  a[0][2]=3;
  a[1][0]=6;
  a[1][1]=2;
  a[1][2]=5;

  for(int i = 0; i < 2; i++) {
    sort(a[i],a[i]+3);
  }

  for(int row = 0; row < 2; row++) {
    for(int col = 0; col < 2; col++) {
      cout << a[row][col] << " ";
    }
  }

  return 0;
}

I initiated every element of your multidimensional array a , since your declared a to be size 6 (2 rows, 3 columns). This would output 1 3 7 2 5 6 , because it sorts the rows from least to greatest. If you wanted to sort the multidimensional array so that the output would read 1 2 3 5 6 7 then you would need to do something like this:

#include <iostream>


using namespace std;

int main(){

  int a[2][3];
  int b[6];
  int count = 0;

  a[0][0]=1;
  a[0][1]=7;
  a[0][2]=3;
  a[1][0]=6;
  a[1][1]=2;
  a[1][2]=5;

  for(int row = 0; row < 2; row++) {
    for(int col = 0; col < 3; col++) {
      b[count] = a[row][col];
      count++; 
    }
  }

  sort(b, b+6);
  count = 0;

  for(int row = 0; row < 2; row++) {
    for(int col = 0; col < 3; col++) {
      a[row][col] = b[count];
      count++;
    }
  }

  for(int row = 0; row < 2; row++) {
    for(int col = 0; col < 3; col++) {
      cout << a[row][col] << " ";
    }
  }

  return 0;
}

This second example is probably the worst possible way to go about sorting a multidimensional array though. Let me know if you find an error in my code, I was unable to test, or need additional help.

As the multidimensional arrays are contiguous you can also try:

int main()
{
  int a[2][3];

  a[0][0]=1;
  a[0][1]=7;
  a[0][2]=3;
  a[1][0]=6;
  a[1][1]=2;
  a[1][2]=5;

  std::sort(&a[0][0], &a[1][3]);

  for(int row = 0; row < 2; row++) {
    for(int col = 0; col < 3; col++) {
      std::cout << a[row][col] << " ";
    }
  }
}

Depending on what you want. It is also possible to write a begin() and end() for multidimensional arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM