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

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

程序代码如下:

#include <vector>#include <iostream>#include <string>#include <algorithm>using namespace std;//comparison function to be userd to sort by word lengthbool isShorter(const string &s1,const string &s2){return s1.size()<s2.size();}//determine whether a length of a given word is 6 or morebool Gt6(string str){return str.size()>=6;}//odd or pluralstring make_plural(int w,string param,string postfix){if(w>1)return param+postfix;elsereturn 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 duplicatessort(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 sizestable_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;}

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

突然之间失去了语言。那才是真正的寂寞,

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

相关文章:

你感兴趣的文章:

标签云: