假设我们要分析一组儿童故事中使用的单词,例如想知道他们使用了多少个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; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-08 18:04:34