[英]Multi-Dimensional Array sorting in c++
I am using sort() function for single array it works well. 我对单个数组使用sort()函数,效果很好。
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. 使用您的代码只需在多维数组的每一行上使用
std::sort
。 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). 我启动了多维数组
a
每个元素,因为您声明a
大小为6(2行3列)。 This would output 1 3 7 2 5 6
, because it sorts the rows from least to greatest. 这将输出
1 3 7 2 5 6
,因为它将从最小到最大对行进行排序。 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: 如果要对多维数组进行排序,以使输出读取为
1 2 3 5 6 7
则需要执行以下操作:
#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. 也可以为多维数组编写
begin()
和end()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.