/*
功能实现
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;
}
C++容器排序算法的简单应用
最新推荐文章于 2022-06-18 16:29:08 发布