map<> 解析总结

一、计算每个字符串出现的次数

#include "stdafx.h"

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
using namespace std;

int main()
{
//	string strInput = "我 爱 吃 苹果 , 我 更 爱 吃 香蕉 。 ";
	string strInput = "liulina.bmp dd.bmp lina.bmp dd.bmp doudoumama.bmp liulina.bmp gong.bmp doudoumama.bmp dd.bmp liulina.bmp dd.bmp liulina.bmp liulina.bmp doudoumama.bmp dd.bmp";

	map<string, int> mapWords; // 存放词以及频率   
	unsigned int pos1 = 0;  
	unsigned int pos2 = 0;  
	pos2 = strInput.find(" ", pos1);  
	string strWord;  
	while(pos2 != string::npos)  
	{  
		strWord = strInput.substr(pos1, pos2 - pos1);  
		mapWords[strWord]++;  
		pos1 = pos2 + 1;  
		pos2 = strInput.find(" ", pos1);  
	}  
	
	// 在屏幕上进行打印  
	map<string, int>::iterator iter;  
	for(iter = mapWords.begin(); iter != mapWords.end(); ++iter)  
	{  
		cout << iter->first << "     "  
			<< iter->second << endl;  
	}  
	
	return 0;
}
结果:

dd.bmp     4
doudoumama.bmp     3
gong.bmp     1
lina.bmp     1
liulina.bmp     5



二、C++ map排序(按照value值排序) 将map中的key和value分别存放在一个pair类型的vector中

#include "stdafx.h"

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
using namespace std;

typedef pair<string, int> PAIR;  

bool cmp_by_value(const PAIR& lhs, const PAIR& rhs) 
{  
	return lhs.second > rhs.second;  
} 

int main() {  
	map<string, int> name_score_map;  
	name_score_map["LiMin"] = 90;  
	name_score_map["ZiLinMi"] = 79;  
	name_score_map["BoB"] = 92;  
	name_score_map.insert(make_pair("Bing",99));  
	name_score_map.insert(make_pair("Albert",86));  
	//把map中元素转存到vector中   
	vector<PAIR> name_score_vec(name_score_map.begin(), name_score_map.end());  
	sort(name_score_vec.begin(), name_score_vec.end(), cmp_by_value);  
	 
	for (int i = 0; i < name_score_vec.size(); ++i)
	{  
		cout << name_score_vec[i].first<<"    "<<name_score_vec[i].second << endl;  
	}  
	
	return 0;  
}  

结果:按int 值降序排列

Bing    99
BoB    92
LiMin    90
Albert    86
ZiLinMi    79

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值