Use the map

First, the header file include <map>

 

Second, create a map variable map <key, value> mp; wherein key, value of any type. And is the only key, value is a value corresponding key.

a map used to calculate the number of each string of characters that appear easily, may also calculate the number of word appears.

 

Three, map traversal

#include <the iostream> 
#include <Vector> 
#include <Map> 
#include < String > 
#include <the cmath> 
#include <algorithm>
 #define LL Long Long the using namespace STD; int main () { String STR = " HelloWorld " ; 
    Map < char , int > MP;
       number of occurrences of the characters // calculated, and sorted according to the dictionary
     for ( int I = 0 ; I <str.size (); I ++ )
         ++ MP [STR [I]];

 



    
    
map<char,int>::iterator iter; iter = mp.begin(); while(iter != mp.end()) { cout << (iter->first) << ":" << (iter->second) << endl; iter++; } return 0; }

operation result:

 

 

 

 

Four, map sorting

Since each element in the map type pair (pair <key, value>), map composed by the pair number, and sorted by the dictionary.

So put all the elements ready to move the map in the array is sorted.

#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <cmath>
#include <algorithm>
#define ll long longusingnamespace std;int cmp(pair<char,int> p1, pair<char,int> p2) {
    return p1.second > p2.second;
}int main() {string str = "helloworld"; 
    map<four

 




    
    , Int > MP;
     // use a fixed array 
 //     pair <char, int> PRS [100];
     // use Vector 
    Vector <pair < char , int >> PRS; 
    
    for ( int I = 0 ; I <str.size (); I ++ )
         ++ MP [STR [I]]; 
        
    Map < char , int > :: Iterator ITER; 
    ITER = mp.begin (); 
    
    //   Map transfected into an array 
    the while ! (ITER = mp.end () ) { 
        prs.push_back (pair < char,int>((iter->first), (iter->second)));
        iter++;
    }
    
    // 排序 
    sort(prs.begin(), prs.end(), cmp);
    
    for(int i = 0; i < prs.size(); i++)
        cout <<  prs[i].first << ":" << prs[i].second << endl; 
    
    return 0;
}

operation result:

Guess you like

Origin www.cnblogs.com/hello-dummy/p/12070166.html