如何使用stl排序函数根据第二列对2d数组进行排序

How to sort a 2d array according to the second column using stl sort function?

本文关键字:排序 二列 2d 数组 函数 stl 何使用      更新时间:2023-10-16

如何使用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/