Advertisement

英文单词排序

阅读量:

题目:

请编写一段程序来读取一组英文单词,并将这些单词按照长度从短到长排序后输出结果。当长度相同时,请按照输入的原始顺序进行处理。

输入格式:

a highly efficient algorithm has been developed

输出格式:

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

输入样例:

blue
red
yellow
green
purple

输出样例:

red blue green yellow purple

代码:
复制代码
    #include <bits/stdc++.h>
    using namespace std;
    struct node
    {
    string s;
    int id;
    };
    
    int main()
    {
    vector<node> v;
    for (int i = 0;; i++)
    {
        string s;
        cin >> s;
        if (s == "#")
            break;
        v.push_back({s, i});
    }
    auto cmp = [](node &e1, node &e2) {
        int a = e1.s.length();
        int b = e2.s.length();
        return tie(a, e1.id) < tie(b, e2.id);
    };
    sort(v.begin(), v.end(), cmp);
    for (int i = 0; i < v.size(); i++)
    {
        cout << v[i].s << " ";
    }
    return 0;
    }
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    AI写代码

全部评论 (0)

还没有任何评论哟~