-
容器map是一种关联数组,是键值对的集合,一个键只能对应一个值,可以通过键为下标获取对应的值。multimap一个键可以对应多个值。
-
key和value必须是可赋值和可复制的,对象以数据对的形式存放在二叉树中。
-
初始化,清空,删除,插入等基本操作
#include <iostream>
#include <map> //包含头文件
using namespace std;
//以给定的排序准则定义map,
map<int, double> m1; //使用默认排序准则,默认为less<>
map<int, double, greater<int>> m2; //用模板参数定义排序准则
//插入键值对,当插入时会自动按照排序准则对键进行排序,如下面遍历时所示
m1.insert(pair<1, 2.0>); //这种方式插入到末尾
m1.insert(m1.begin(),pair<2, 2.0>) //将数据对插入到迭代器之前
m1.insert(m2.begin(), m2.end()); //将迭代器指定范围的数据对插入
//删除键值对
m1.erase(m1.begin()); //删除迭代器指向的数据对
m1.erase(m1.begin(), m1.end()); //删除迭代器指定范围的数据对
m1.erase(1); //删除指定键对应的数据对
//map不支持元素直接存取,元素存取要用迭代器进行实现
void PrintL(map<int, double>& m)
{
map<int, double>::iterator it;
for(int i = m.begin(); it != m.end(); ++i)
{
pair<int, double> p1 = (pair<int, double>)(*it)
cout << p1.first << ", " << p1.second << endl;
}
}
void PrintG(map<int, double, greater<int>>& m)
{
map<int, double, greater<int>>::iterator it;
for(int i = m.begin(); it != m.end(); ++i)
{
pair<int, double> p1 = (pair<int, double>)(*it)
cout << p1.first << ", " << p1.second << endl;
}
}
PrintL(m1);
PrintG(m2);
int size = m1.size(); //返回当前的数据成员数量
int maxSize = m1.max_size(); //返回最大的数据成员数量
bool ifEmpty = m1.empty(); //判断是否为空
m1.clear(); //删除容器中所有的元素 earse(map::begin(), map::end())
- 查找算法
//使用STL通用算法,find()可用于查找map中的指定键值的数据对,find_if()用于有条件查找,如果键值对应的元素不存在,则返回end()
map<int, double> m1;
pair<int, double> temp;
map<int, double>::iterator it;
it = find(m1.begin(), m1.end(), 1);
it = find_if(myvt.begin(), myvt.end(), bind2nd(greater<int>(),5));
temp = (*it);
cout << temp.first << " " << temp.second;
//还可以使用成员函数find()
it = m1.find(5);
//count()用于查找容器中指定键值的数据对个数
map<int, double> m1;
multimap<int, double> m2;
int a = m1.count(1); //a为0或1
int b = m2.count(1); //b可能为其他值
- 对象交换,两map/multimap容器中元素类型不同时不能交换
map<int, double> m1;
map<int, double> m2;
m1.swap(m2); //注意仅myvt1的内容发生变化
swap(m1, m2); //都发生变化
- 判断容器中元素排列规则(不常用)
key_compare kep_comp() const; //键值比较
value_compare value_comp() const; //实值比较
- 获取内存分配器,内存分配器类似指针的首地址,用于指明对象的初始存储位置。在定义map时可指定使用某内存分配器。
map<int, double> m1;
map<int, double>::allocator_type m1_alloc;
map<int, double>::allocator_type m2_alloc;
m1_alloc = m1.get_allocator();
map<int, double> m2(less<int>(), m1_alloc);
m2_alloc = m2.get_allocator();
bool a = (m1_alloc == m2_alloc)? 1 : 0; //a = true