【发布时间】:2013-12-16 18:13:48
【问题描述】:
如何使用stl排序函数根据第二列对二维数组进行排序?
例如
如果我们有一个数组 a[5][2] 并且我们想根据 ar[i][1] 条目进行排序,我们如何使用 stl 排序函数来完成它。我知道我们必须使用布尔函数作为第三个参数传递,但我无法设计适当的布尔函数?
【问题讨论】:
标签: c++ sorting multidimensional-array stl 2d
如何使用stl排序函数根据第二列对二维数组进行排序?
例如
如果我们有一个数组 a[5][2] 并且我们想根据 ar[i][1] 条目进行排序,我们如何使用 stl 排序函数来完成它。我知道我们必须使用布尔函数作为第三个参数传递,但我无法设计适当的布尔函数?
【问题讨论】:
标签: c++ sorting multidimensional-array stl 2d
stl 排序要求将迭代器的右值作为参数传递。如果要使用排序功能,则必须在 c++11 中编译并使用数组 stl 来存储数组。代码如下
#include "bits/stdc++.h"
using namespace std;
bool compare( array<int,2> a, array<int,2> b)
{
return a[0]<b[0];
}
int main()
{
int i,j;
array<array<int,2>, 5> ar1;
for(i=0;i<5;i++)
{
for(j=0;j<2;j++)
{
cin>>ar1[i][j];
}
}
cout<<"\n earlier it is \n";
for(i=0;i<5;i++)
{
for(j=0;j<2;j++)
{
cout<<ar1[i][j]<<" ";
}
cout<<"\n";
}
sort(ar1.begin(),ar1.end(),compare);
cout<<"\n after sorting \n";
for(i=0;i<5;i++)
{
for(j=0;j<2;j++)
{
cout<<ar1[i][j]<<" ";
}
cout<<"\n";
}
return 0;
}
在c++11中编译可以通过g++ -std=c++11 filename.cpp -o out来完成。 如果您不想使用 c++11 或使用“数组”stl,请使用 std::qsort 函数。有了这个,您可以使用传统的方式来定义数组,如 int a[10][2]。代码如下
#include "bits/stdc++.h"
using namespace std;
int compare( const void *aa, const void *bb)
{
int *a=(int *)aa;
int *b=(int *)bb;
if (a[0]<b[0])
return -1;
else if (a[0]==b[0])
return 0;
else
return 1;
}
int main()
{
int a[5][2];
cout<<"enter\n";
for(int i=0;i<5;i++)
{
for(int j=0;j<2;j++)
{
cin>>a[i][j];
}
//cout<<"\n";
}
cout<<"\n\n";
qsort(a,5,sizeof(a[0]),compare);
for(int i=0;i<5;i++)
{
for(int j=0;j<2;j++)
{
cout<<a[i][j]<<" ";
}
cout<<"\n";
}
return 0;
}
【讨论】:
制作自己的比较功能。
请参阅 std::sort() 的初学者指南。 http://www.cplusplus.com/articles/NhA0RXSz/
【讨论】: