字符串长度排序

题目描述
先输入你要输入的字符串的个数。然后换行输入该组字符串。每个字符串以回车结束,每个字符串少于一百个字符。 如果在输入过程中输入的一个字符串为“stop”,也结束输入。 然后将这输入的该组字符串按每个字符串的长度,由小到大排序,按排序结果输出字符串。

输入描述:
字符串的个数,以及该组字符串。每个字符串以‘\n’结束。如果输入字符串为“stop”,也结束输入.

输出描述:
可能有多组测试数据,对于每组数据,
将输入的所有字符串按长度由小到大排序输出(如果有“stop”,不输出“stop”)。

根据输入的字符串个数来动态分配存储空间(采用new()函数)。每个字符串会少于100个字符。
测试数据有多组,注意使用while()循环输入。

示例1
输入
5
sky is grey
cold
very cold
stop
3
it is good enough to be proud of
good
it is quite good

输出
cold
very cold
sky is grey
good
it is quite good
it is good enough to be proud of

题目解析:字符串排序,也就是按输入的字符串的长度进行排序,所以记录字符串和他的长度,然后按长度进行输出就行了。

代码:

#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<iostream>
#include<vector>
#include<map>
#include<iomanip>
using namespace std; 

bool cmp(pair<string,int> p1,pair<string,int> p2){   //按长度进行比较 
	return p1.second < p2.second;
}
int main()
{
	int count;
	string str;
	vector<pair<string,int>> vc;    //记录字符串和长度 
	while(cin >> count){
		cin.ignore();   //忽略回车 
		for(int i = 0; i < count ;i++){
			getline(cin,str);
			if(str != "stop"){
				vc.push_back(make_pair(str,str.size()));
			}else{
				break;
			}
		}
		sort(vc.begin(),vc.end(),cmp);
		for(int i = 0; i <  vc.size(); i++){
			cout << vc[i].first << endl;
		}
		vc.clear();
	} 
    return 0;
}
发布了41 篇原创文章 · 获赞 0 · 访问量 1176

猜你喜欢

转载自blog.csdn.net/Gedulding/article/details/104325005