目录
map容器
介绍:
(1)map容器中所有元素都是pair
(2)pair的第一个元素是key值,索引作用。
(3)pair的第二个元素是value值,实际值。
(4)所有元素会根据key值自动排序(默认升序)。
(5)map不可重复,multimap可重复。
(6)map不允许插入重复的key。
本质:
·关联式容器 二叉树实现。
优点:
·可通过key值快速找到value值。
构造函数
根据键值升序排序
void print(map<int,int> m) { for (map<int, int>::iterator beg = m.begin(); beg != m.end(); beg++) cout << "key=" << (*beg).first << " value=" << (*beg).second << endl; cout << endl; } void test() { map<int, int>m; m.insert(pair<int, int>(1, 10)); m.insert(pair<int, int>(4, 30)); m.insert(pair<int, int>(2, 40)); m.insert(pair<int, int>(3, 20)); print(m); }
m.insert(pair<int, int>(1, 10));//这里不能省略pair,否则会报错 c2100
运行结果:
key=1 value=10 key=2 value=40 key=3 value=20 key=4 value=30
拷贝构造
map<int, int>m2(m);
赋值
map<int, int>m; map<int, int>m2; m2 = m;
大小和交换
大小
cout << m.size();
是否为空
cout << m.empty();
交换
map<int, int>m; map<int, int>m2; m.swap(m2);
插入与删除
插入
m.insert(pair<int, int>(1, 10));
m.insert(make_pair(2, 20));
删除
m.erase(3);
(按照键值删除。若找不到键值,不会执行操作)
区间删除
map<int, int>::iterator beg = m.begin(); beg++; m.erase(beg,m.end());//<--------------------
查找和统计
查找
m.find(x);
map的find返回值类型是迭代器
void test() { map<int, int>m; m.insert(make_pair(1, 15)); m.insert(make_pair(2, 20)); m.insert(make_pair(3, 20)); map<int, int>::iterator f = m.find(2); cout << (*f).first << (*f).second << endl; print(m); }
运行结果:
2 20 key=1 value=15 key=2 value=20 key=3 value=20
统计
返回值类型为整型。因为不是multimap,所以要么1,要么0。
m.count(2);
排序
默认升序。
降序:将仿函数名加入到< >中
class Mycompare { public: bool operator()(int v1,int v2)const { return v1 > v2; } }; void print(map<int, int, Mycompare> m) { for (map<int, int, Mycompare>::iterator beg = m.begin(); beg != m.end(); beg++) cout << "key=" << (*beg).first << " value=" << (*beg).second << endl; cout << endl; } void test() { map<int, int, Mycompare>m; m.insert(make_pair(1, 15)); m.insert(make_pair(2, 20)); m.insert(make_pair(3, 25)); print(m); }
(第三行尾加了const就不报错了)
运行结果:
key=3 value=25 key=2 value=20 key=1 value=15
实例思路:公司员工分组
公司实例用的是multimap。
用vector创建好员工表(自定义类型,成员属性有部门号和名字等。)
用multimap的insert功能 根据员工表 添加部门号和名字。(部门号为键值。自动排序)
用count方法统计一个部门有多少人。