Suppose we want to analyze a group of words used in children's stories, such as how many 6 or more letters they use. Each word is counted only once, regardless of how many times it appears.
The program code is as follows:
#include <vector> #include <iostream> #include <string> #include <algorithm>using namespace std ;//comparison function to is 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 this 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 t He 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;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The algorithm for reordering container elements