C++容器排序算法的简单应用

/*
功能实现
1.去掉所有重复的单词
2.按照单词的长度进行排序
3.统计长度等于或者超过6个字符的单词个数
4.按照单词的长度顺序进行输出
*/
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>

using namespace std;

bool isShorter(const string &s1 , const string &s2)
{
	return s1.size() < s2.size();
}

bool GT6(const string &s)
{
	return s.size() >= 6;
}
string make_plural(vector<string>::size_type cnt , string s1 , string s2)
{
	return (cnt == 1) ? s1 : s1+s2;  
}
int main()
{
	typedef vector<string>::iterator iter;
	typedef vector<string>::size_type sz_type;
	vector<string> words;
	string next_word;
	//输入单词
	while(cin >> next_word && next_word != "0")
	{//当输入0时结束
		words.push_back(next_word);
	}
	//对单词进行排序,按照字典序进行排列
	sort(words.begin() , words.end());
	//去掉重复的单词
	iter end_unique = unique(words.begin() , words.end());
	words.erase(end_unique , words.end());
	//对剩下没有重复的单词进行长度排序,长度相等的进行字典序排列
	stable_sort(words.begin() , words.end() , isShorter);
	//按长度输出剩下的单词
	for(iter it = words.begin() ; it != words.end() ; ++it)
	{
		cout << *it  << "  ";
	}
	cout << endl;
	//找到单词长度大于等于6个字符的个数
	sz_type wc = count_if(words.begin() , words.end() , GT6);
	cout << wc << make_plural(wc , "time" , "s") << endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值