文章

7

粉丝

0

获赞

13

访问

185

头像
字符串排序3 题解:使用vector +sort(),此方法适用于多种场景
P1261 北京大学机试题
发布于2025年3月10日 12:49
阅读数 46

使用vector +sort(),此方法适用于多种场景,对此不熟悉的可记为这类相关问题的通解

#include <bits/stdc++.h>

using namespace std;
// 自定义比较函数
bool cmp(const string &a,const string &b){
	if(a.length()==b.length()){
		return a<b;
	}
	return a.length()<b.length();
}


int main() {
   int n;
   vector<string> vc;
   while(cin>>n){
   	cin.ignore();//避免读入换行
   	while(n--){
   		string str;
   		getline(cin,str);
   		if(str !="stop"){
   		vc.push_back(str);
   	}else{
   		break;
	   }
   		
	   }
	sort(vc.begin(),vc.end(),cmp);
	for(const string &s : vc){
		cout<<s<<endl;
	}
   	vc.clear();//vector清0
   	
   }
   return 0;
   
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发