map 的使用

一、加入头文件 include <map>

二、创建map变量 map<key, value> mp; 其中key、value为任意类型。而key是唯一的,value为key对应的值。

map用来计算一个字符串中各个字符出现的次数很方便,还可以计算单词出现的次数。

三、map的遍历

#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <cmath>
#include <algorithm>
#define ll long long

using namespace std;


int main() {
    
    string str = "helloworld"; 
    map<char, int> mp;
    
  // 计算字符的出现的次数,而且按字典排序
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; }

运行结果:

四、map的排序

因为map中的每个元素是pair类型(pair<key,value>),map是由很多pair组成,而且按字典排序。

所以把准备好的map中的全部元素移到数组中进行排序。

#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <cmath>
#include <algorithm>
#define ll long long

using namespace std;

int cmp(pair<char,int> p1, pair<char,int> p2) {
    return p1.second > p2.second;
}

int main() {
    
    string str = "helloworld"; 
    map<char, int> mp;
    // 使用固定数组 
//    pair<char,int> prs[100];
    // 使用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转成数组 
    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;
}

运行结果:

猜你喜欢

转载自www.cnblogs.com/hello-dummy/p/12070166.html