First, let's talk about counting the number of letters.
Since the letters are 26 free, we can create a new array to hold the number of individual letters.
#include <iostream>using namespacestd;/** * Count the number of letters*/intMain () {Chars[ the] ="Hello world!"; intc[ -] = {0 }; //first uniform to lowercase for(inti =0; S[i]; i++) if(S[i] >='A'&& S[i] <='Z') S[i]= S[i]-'A'+'a'; //count the number of letters by creating a new array for(inti =0; S[i]; i++) if(S[i] >='a'&& S[i] <='Z') C[s[i]-'a']++; //Print Results for(inti =0; i< -; i++) cout<<Char('a'+ i) <<":"<< C[i] <<" "; cout<<Endl; return 0;}
Second, the counting Sort method
Counting sorting is very much related to the above example, we first need to find the maximum value of the array to be sorted max, and then create an array containing the number of max+1 to hold the number of 0~max numbers. The array is then traversed from the beginning to sort the original array.
#include <iostream>#include<vector>using namespacestd;/** * Counting sorting method*/intMain () {intA[] = {4,6,6,4,6,4,9,1,5,6};//arbitrary Array intMax =0; //Find Max Max for(inti =0; I! = (sizeof(a)/sizeof(int)); ++i) {if(a[i]>max) Max=A[i]; } //set up a 0~max vector to hold the number of numbersvector<int>ivec (max +1,0); for(inti =0; I! = (sizeof(a)/sizeof(int)); ++i) {Ivec[a[i]]++; } //test whether the above conversions are correct//for (int i=0;i!=ivec.size (); ++i)//cout<<ivec[i]<<endl; for(inti =0, j =0; J! = Ivec.size () && i< (sizeof(a)/sizeof(int)); ++j) { while(ivec[j]>0) {Ivec[j]--; A[i++] =J; } } //Test for(inti =0; I! = (sizeof(a)/sizeof(int)); ++i) cout<< A[i] <<" "; cout<<Endl;}
Third, the number of statistics
Finally speaking about the number of statistics, the number of statistics can refer to the above approach, but when the number is large, it is not too good to operate, so we can use map to help us, map has key-value, we can take the statistics we need as a map key, Put the number of numbers in key for the value.
#include <iostream>#include<map>using namespacestd;/** * Number of statistics*/intMain () {intA[] ={1,5,1,2,3,2,10000000};//arbitrary Arraymap<int,int>m; //Number of digits stored for(inti =0; i< (sizeof(a)/sizeof(int)); i++) M[a[i]]++; //Print Results for(map<int,int>::iterator It=m.begin (); It!=m.end (); ++it) cout<< It->first <<"the number is"<<':'<< It->second <<Endl; /** * Find a specific number and print out the number of **map<int, int>::iterator it = m.find (1); **if (It! = M.end ()) * * cout << it->second; */ return 0;}
Reference: http://www.csie.ntnu.edu.tw/~u91029/index.html
Count Sort Implementation