#44975: cpp 超級簡單解


1121232@stu.wghs.tp.edu.tw (Ian911436)

學校 : 臺北市私立薇閣高級中學
編號 : 258883
來源 : [60.248.154.143]
最後登入時間 :
2025-06-20 09:40:35

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

bool compare(const string &a, const string &b) {
    // 先比較長度,如果長度相同,再按字母順序排序
    if (a.size() == b.size()) {
        return a < b;  // 字母順序排序
    }
    return a.size() < b.size();  // 按長度排序
}

int main() {
    int n;
    cin >> n;  // 讀取名字的數量
    cin.ignore();  // 忽略換行符號

    vector<string> names(n);
    for (int i = 0; i < n; ++i) {
        getline(cin, names[i]);  // 讀取每行名字
    }

    // 使用自定義的比較函數進行排序
    sort(names.begin(), names.end(), compare);

    // 輸出排序後的名字
    for (const auto &name : names) {
        cout << name << endl;
    }

    return 0;
}

#46407: Re: cpp 超級簡單解


1121226@stu.wghs.tp.edu.tw (Arthur✨EC)

學校 : 臺北市私立薇閣高級中學
編號 : 252772
來源 : [60.248.154.139]
最後登入時間 :
2025-08-21 12:59:45

#include<bits/stdc++.h>
using namespace std;
int main(){
    int n;
    cin>>n;
    cin.ignore(); // 忽略換行符
    vector<string> names(n);
    for(int i=0;i<n;i++){
        getline(cin,names[i]);
    }
    // 自定義排序函數
    sort(names.begin(),names.end(),[](const string& a,const string& b){
        // 先按長度排序
        if(a.length()!=b.length()){
            return a.length()<b.length();
        }
        // 長度相同時按字母順序排序
        return a<b;
    });
    // 輸出結果
    for(const string& name:names){
        cout<<name<<endl;
    }
    return 0;
}