map(程序设计与算法(一))

一、用法

与multiset和set的区别类似,但多了一个可以使用[ ],这十分好用

二、应用

(1)

#include<iostream>
#include<string>
#include<map>
using namespace std;
struct Student
{
	string name;
	int score;
};
Student students[5] = { {"Jack",89} ,{"Tom",74},{"Cindy",87},{"Alysa",87},{"MIcheal",98} };
typedef map<string, int> MP;
int main()
{
	MP mp;
	for (int i = 0; i != 5; ++i)
		mp.insert(make_pair(students[i].name, students[i].score));  //插入map中要make_pair转为pair类型
	cout << mp["Jack"] << endl;  
	mp["Jack"] = 69; //修改Jack的分数
	for (auto i = mp.begin(); i != mp.end(); ++i)   //和multimap一样以first排序
		cout << "(" << i->first << "," << i->second << ") ";
	cout << endl;
	Student st;
	st.name = "Jack";
	st.score = 99;
	auto p = mp.insert(make_pair(st.name, st.score));  //和set一样,插入返回的是一个含迭代器和bool型的pair
	if (p.second)      //second是bool类型,若真进行以下操作
		cout << "(" << p.first->first << "," << p.first->second << ") inserted" << endl;
	else
		cout << "insertion failed" << endl;
	mp["Harry"] = 78;    //[]若无对应的first则是插入一个struct元素
	auto q = mp.find("Harry");
	cout << "(" << q->first << "," << q->second << ")" << endl;
	system("pause");
}

(2)

#include<iostream>
#include<string>
#include<map>
#include<set>
using namespace std;
struct Word
{
	int times;
	string wd;
};
struct Rule    //自定义排序规则
{
	bool operator()(const Word & w1, const Word & w2)  //注意是Word类型
	{
		if (w1.times != w2.times)
			return w1.times > w2.times;
		else
			return w1.wd < w2.wd;
	}
};
int main()
{
	string s;
	set<Word, Rule> st;
	map<string, int> mp;
	while (cin >> s)  //注意[]!若有本就存在的字符串就递增次数(second),不存在则插入再递增
		++mp[s];    //这比排序再二分查找添加/递增快速的多
	for (auto i = mp.begin(); i != mp.end(); ++i)
	{
		Word tmp;
		tmp.times = i->second;
		tmp.wd = i->first;
		st.insert(tmp);    //将其插入set中按自定义排序规则排序
	}
	for (auto i = st.begin(); i != st.end(); ++i)
		cout << i->wd << " " << i->times << endl;
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/weixin_44009743/article/details/87616222