C++ 如何使用stl排序函数根据第二列对二维数组进行排序?
如何使用stl排序函数根据第二列对二维数组进行排序 例如C++ 如何使用stl排序函数根据第二列对二维数组进行排序?,c++,sorting,multidimensional-array,stl,2d,C++,Sorting,Multidimensional Array,Stl,2d,如何使用stl排序函数根据第二列对二维数组进行排序 例如 如果我们有一个数组a[5][2],并且我们希望根据ar[i][1]条目进行排序,那么如何使用stl排序函数进行排序。我知道我们必须使用布尔函数作为第三个参数传递,但我无法设计适当的布尔函数?制作您自己的比较函数 请参阅std::sort()初学者指南。 stl排序要求将迭代器的右值作为参数传递。如果你想使用排序函数,你必须在c++11中编译并使用数组stl来存储数组。代码如下 #include "bits/stdc++.h" using
如果我们有一个数组a[5][2],并且我们希望根据ar[i][1]条目进行排序,那么如何使用stl排序函数进行排序。我知道我们必须使用布尔函数作为第三个参数传递,但我无法设计适当的布尔函数?制作您自己的比较函数 请参阅std::sort()初学者指南。
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;
}
#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;
}
#包括“bits/stdc++.h”
使用名称空间std;
布尔比较(数组a、数组b)
{
返回[0]