码迷,mamicode.com
首页 > 其他好文 > 详细

sort对二维字符数组排序(转)

时间:2014-08-24 11:35:52      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   for   ar   div   代码   

由于二维字符数组的第二维没有赋值运算符,即不能对整个一维数组进行赋值,因此是无法直接对二维数组用sort进行排序的,解决办法有二种:

代码一:

 

 1 #include <iostream>
 2 #include <cstring>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 struct Data
 7 {
 8     char data[100];    
 9 }str[100];
10 
11 bool cmp(const Data &elem1, const Data &elem2)
12 {
13     if (strcmp(elem1.data, elem2.data) < 0)
14         return true;
15     return false;
16 }
17 
18 
19 int main()
20 {
21     int n, i;
22     while (cin>>n)
23     {
24         for (i=0; i<n; ++i)
25         {
26             cin>>str[i].data;
27         }
28         
29         sort(str, str+n, cmp);
30         
31         for (i=0; i<n; ++i)
32             cout<<str[i].data<<endl;
33     }
34     return 0;
35 }

 

 

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

代码二:

 

 1 bool cmp(const char *elem1, const char *elem2)
 2 {
 3     if (strcmp(elem1, elem2) < 0)
 4         return true;
 5     return false;
 6 }
 7 
 8 int main()
 9 {
10     char str[100][100];
11     char *pStr[100] = {NULL};
12     int n, i;
13     while (cin>>n)
14     {
15         for (i=0; i<n; ++i)
16         {
17             cin>>str[i];    
18             pStr[i] = str[i];
19          }
20         sort(pStr, pStr+n, cmp);
21         for (i=0; i<n; ++i)
22             cout<<pStr[i]<<endl;
23     }
24     return 0;
25 }

 


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

sort对二维字符数组排序(转)

标签:style   blog   color   os   io   for   ar   div   代码   

原文地址:http://www.cnblogs.com/catdrivedragon/p/3932599.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!