sort对二维字符数组排序

转载自(http://blog.csdn.net/unimen/article/details/6843977)
由于二维字符数组的第二维没有赋值运算符,即不能对整个一维数组进行赋值,因此是无法直接对二维数组用sort进行排序的,解决办法有二种:

代码一:

 #include <iostream>  
    #include <cstring>  
    #include <algorithm>  
    using namespace std;  

    struct Data  
    {  
        char data[100];   
    }str[100];  

    bool cmp(const Data &elem1, const Data &elem2)  
    {  
        if (strcmp(elem1.data, elem2.data) < 0)  
            return true;  
        return false;  
    }  


    int main()  
    {  
        int n, i;  
        while (cin>>n)  
        {  
            for (i=0; i<n; ++i)  
            {  
                cin>>str[i].data;  
            }  

            sort(str, str+n, cmp);  

            for (i=0; i<n; ++i)  
                cout<<str[i].data<<endl;  
        }  
        return 0;  
    }  

利用上面的方法将将数组放到结构体中,结构体中,这样赋值操作符就可用了,结构体中的数组可以进行整体赋值

代码二:

    bool cmp(const char *elem1, const char *elem2)  
    {  
        if (strcmp(elem1, elem2) < 0)  
            return true;  
        return false;  
    }  

    int main()  
    {  
        char str[100][100];  
        char *pStr[100] = {NULL};  
        int n, i;  
        while (cin>>n)  
        {  
            for (i=0; i<n; ++i)  
            {  
                cin>>str[i];    
                pStr[i] = str[i];  
            }  
            sort(pStr, pStr+n, cmp);  
            for (i=0; i<n; ++i)  
                cout<<pStr[i]<<endl;  
        }  
        return 0;  
    }  

这样也可以实现对二维数组进行排序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值