码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-07-05 09:43:39      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

假设我们要分析一组儿童故事中使用的单词,例如想知道他们使用了多少个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;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

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

标签:

原文地址:http://blog.csdn.net/sxhlovehmm/article/details/46757171

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!