文章

28

粉丝

0

获赞

497

访问

30.1k

头像
国名排序 题解:依旧sort+自定义比较函数
P1217 同济大学机试题
发布于 2026年2月
阅读数 989

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;


//比较函数

bool cmp(const string &a,const string &b){

  size_t i=0;

  size_t len1=a.size();

  size_t len2=b.size();

//只要字母不同就可以返回

  while(i<len1&&i<len2){

    if(a[i]!=b[i])return a[i]<b[i];

    i++;

  }

  //前缀字母全相同的话,哪个国家字母少哪个排前面

  return len1<len2;

}

int main(){

  int n;cin>>n;

  vector<string> country(n);

  for(int i=0;i<n;i++){

    cin>>country[i];

  }

  sort(country.begin(),country.end(),cmp);

  for(string s:country){

    cout<<s<<"\n";

  }

  return 0;

}

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发