如何使用stl排序函数根据第二列对2d数组进行排序
How to sort a 2d array according to the second column using stl sort function?
如何使用stl排序函数根据第二列对2d数组进行排序?
例如
如果我们有一个数组a[5][2],并且我们想根据ar[i][1]条目进行排序,那么我们如何使用stl排序函数来进行排序。我知道我们必须使用布尔函数作为第三个参数传递,但我无法设计合适的布尔函数?
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或使用"array"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<<"entern";
for(int i=0;i<5;i++)
{
for(int j=0;j<2;j++)
{
cin>>a[i][j];
}
//cout<<"n";
}
cout<<"nn";
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/
相关文章:
- 二叉排序树无法编译
- 对对应于矩阵的行和列的对向量进行排序
- 如何在C++中获取二维数组中最少的一列数?
- 为什么指针在对二维数组进行排序时无法正常工作?
- 绘制二维矩阵的行和列
- 使用 std::sort 对二维 c 数组进行排序
- 如何根据第二列/第三列等对字符串向量进行排序?
- 如何对文件中数组中的单个列进行冒泡排序?C++
- C++按 2 列对多维数组进行排序
- 如何对二维矢量进行排序
- 按列打印二维数组时出现问题
- 在排序文本文件中实现二叉搜索?
- 按第二列对向量的向量进行排序
- 如何将 50 行和 50 列的二维数组编码为一个为元素随机分配星号的函数?
- 将二维数组中的列的值相加
- 在 QTableView 中仅对一列进行排序,而不对其他列进行排序.独立列
- 按一列对二维数组进行气泡排序
- 排序二维结构阵列
- c++按列排序二维向量
- 排序二维数组不触及第二次元