• 英文单词排序


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

    输入格式:

    输入为若干英文单词,每行一个,以#作为输入结束标志。其中英文单词总数不超过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 }

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

  • 相关阅读:
    数据库的......
    数据库
    XML
    网络编程
    I/O系统---流
    周结

    集合,框架
    Spring入门
    Java Wed
  • 原文地址:https://www.cnblogs.com/jiamian/p/10668129.html
Copyright © 2020-2023  润新知