英文单词排序

本题要求编写程序,输入若干英文单词,对这些单词按长度从小到大排序后输出。如果长度相同,按照输入的顺序不变。

输入格式:

输入为若干英文单词,每行一个,以#作为输入结束标志。其中英文单词总数不超过20个,英文单词为长度小于10的仅由小写英文字母组成的字符串。

输出格式:

输出为排序后的结果,每个单词后面都额外输出一个空格。

输入样例:

blue
red
yellow
green
purple
#

输出样例:

red blue green yellow purple 

 

 

第一次用vector   显示测试点3错误

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 #include <algorithm>
 5 
 6 using namespace std;
 7 
 8 bool cmp(string a,string b)
 9 {
10     return a.size()<b.size();
11 }
12 
13 int main()
14 {
15     string str;
16     vector<string> vi;
17     while(cin>>str,str!="#")
18     {
19         vi.push_back(str);
20     }
21     sort(vi.begin(),vi.end(),cmp);
22     for(int i=0;i<vi.size();i++)
23     {
24         cout<<vi[i]<<" ";
25     }
26     return 0;
27 }

 

用结构体数组就过了........

 1 #include<iostream>
 2 #include<string> 
 3 #include<algorithm>
 4 using namespace std;
 5 struct st
 6 {
 7     string a;
 8     int num;
 9 };
10 st s[25];
11 bool cmp(st x,st y)
12 {
13     if(x.a.size()!=y.a.size())
14         return x.a.size()<y.a.size();
15     else return x.num<y.num;
16 }
17 int main()
18 {
19     int n=0;
20     while(cin>>s[n].a&&s[n].a[0]!='#')
21     {
22         s[n].num=n;
23         n++;
24     }
25     sort(s,s+n,cmp);
26     for(int i=0;i<n;i++)
27     {
28         cout<<s[i].a<<" ";
29     }
30 }

 

两个代码基本上相同,现在就想知道,为什么会出错。。。。

转载于:https://www.cnblogs.com/jiamian/p/10668129.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值