如何根据使用STL的排序功能对第二列排序二维数组? [英] How to sort a 2d array according to the second column using stl sort function?

查看:275
本文介绍了如何根据使用STL的排序功能对第二列排序二维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何根据第二列使用STL的排序功能排序的二维数组?

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

有关,例如

如果我们有一个数组a [5] [2],我们要以根据AR [I] [1]项,我们如何做到这一点使用STL的排序功能排序。据我所知,我们必须使用一个布尔函数来传递作为第三个参数,但我不能够设计出合适的布尔函数?

If we have an array a[5][2] and we want to to sort according to the ar[i][1] entry , how do we do it using the stl sort function. I understand we have to use a boolean function to pass as the third parameter but I am not able to design the appropriate boolean function ?

推荐答案

STL的排序要求迭代器被传递参数的右值。如果你想使用排序功能,你将不得不在编译C ++ 11并使用数组STL存储阵列。在code如下:

The stl sort requires the rvalue of the iterator being passed as the arguments. If you wanna use the sort function, you will have to compile in c++11 and use the array stl to store the array. The code is as follows

#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出来。 如果你不想使用C ++ 11或使用阵列STL,使用std ::的qsort功能。有了这个,你可以用传统的方式来定义的数组如int a [10] [2]。在code如下:

Compiling in c++11 can be done by g++ -std=c++11 filename.cpp -o out. In case you do not want to use c++11 or use the "array" stl, use the std::qsort function. With this you can use the traditional way to define the arrays like int a[10][2]. The code is as follows

#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;
   }

这篇关于如何根据使用STL的排序功能对第二列排序二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆