单词排序

题目描述

小红学会了很多英语单词,妈妈为了帮小红加强记忆,拿出纸、笔,把n个单词写在纸上的一行里,让小红看几秒钟后,将这张纸扣在桌子上。妈妈问小红:你能否将这些n个单词按照字典排列的顺序,从小到大写出来?小红按照妈妈的要求写出了答案。现在请你编写程序帮助妈妈检查小红的答案是否正确。注意:所有单词都由小写字母组成,开头字母全都不同,单词两两之间用一个空格分隔。

 

输入

有两行:第一行仅包含一个正整数n(0<n<27)第二行包含n个单词,表示妈妈写出的单词,两两之间用一个空格分隔。
单个单词长度不超过10。

 

输出

仅有一行:针对妈妈写出的单词,按照字典排列的顺序从小到大排成一行的结果,单词两两之间用一个空格分隔。 

 

样例输入

复制样例数据

4
city boy tree student

样例输出

boy city student tree

我只能说一句,这题很🐶,我用char数组各种不过,后来问同学知道了string这个类型,就过了。

附上一波错误答案,正确的在底下。

#include<iostream>
#include<algorithm>
using namespace std;
struct a
 
{
    char name[50];
}danci[10005];
int cmp(struct a x,struct a y)
{
    return x.name[0]<y.name[0];
}
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        scanf("%s",danci[i].name);
    }
    sort(danci,danci+n,cmp);
    for(int i=0;i<n-1;i++)
        printf("%s ",danci[i].name);
    printf("%s",danci[n-1].name);
    //system("pause");
    return 0;
}
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
int main()
{
    string word[100];
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
        cin>>word[i];
    sort(word,word+n);
    for(int i=0;i<n-1;i++)
        cout<<word[i]<<" ";
    cout<<word[n-1]<<endl;
    //system("pause");
    return 0;
}

 

 

 

 

 

posted @ 2018-12-19 20:12  howxcheng  阅读(860)  评论(0编辑  收藏  举报