对容器元素重新排序的算法

假设我们要分析一组儿童故事中使用的单词,例如想知道他们使用了多少个6个或者以上字母组成的单词。每个单词只统计一次,不考虑它出现的次数。

程序代码如下:

#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
//comparison function to be userd to sort by word length
bool isShorter(const string &s1,const string &s2){
	return s1.size()<s2.size();
}

//determine whether a length of a given word is 6 or more
bool Gt6(string str){
	return str.size()>=6;
}

//odd or plural
string make_plural(int w,string param,string postfix){
	if(w>1)
		return param+postfix;
	else
		return param;
}

int main(int argc,char** argv)
{
	string array[]={"the","quick","red","fox","jumps","over","the","slow","red","turtle"};
	vector<string> words(array,array+sizeof(array)/sizeof(string));
	//sort words alphabetically so we can find the duplicates
	sort(words.begin(),words.end());
	/*	eliminate duplicate words
	*	unique reorders words so that each word appears once in the front portion of words
	*	and returns an iterator past the unique range;
	*	erase use a vector operation to remove the nonunique elements
	*/
	vector<string>::iterator enditer=unique(words.begin(),words.end());
	words.erase(enditer,words.end());
	//sort words by size ,but maintain alphabetic order for words of the same size
	stable_sort(words.begin(),words.end(),isShorter);
	int wc=count_if(words.begin(),words.end(),Gt6);
	cout<<wc<<" "<<make_plural(wc,"word","s")<<" 6 characters or longer"<<endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值