STL常用容器
3.9 map/multimap 容器
3.9.1 map基本概念
map
中所有的元素都是pair
,第一个元素为key(键值),起到索引作用,第二个元素为value(实值)。所有的元素会根据元素的键值自动排序。
本质上,map/multimap
属于关联式容器,底层结构是用二叉树实现。
根据key可以快速找到value值,map
容器不允许重复key值元素,而multimap
则可以重复key值。
3.9.2 map构造和赋值
构造:
map<T1,T2> mp; // 默认构造
map(const map &map); // 拷贝构造
赋值:
map& operator=(const map &mp); //重载等号操作符
示例:
#include<iostream>
using namespace std;
#include<map>
void printMap(const map<int,int> &m)
{
for(map<int,int>::const_iterator it = m.begin();it!=m.end();it++)
{
cout << "key:" << (*it).first << " "
<< "value:"<< it->second << endl;
}
}
void test01()
{
//创建map容器
map<int,int> m;
// 插值
m.insert(pair<int,int>(1,10)); // 匿名对组
m.insert(pair<int,int>(3,30)); // 所有元素都是成对出现(键值对),插入数据用对组
m.insert(pair<int,int>(4,40));
m.insert(pair<int,int>(2,20));
m.insert(pair<int,int>(5,50));
// 输出
printMap(m);
// 拷贝构造
map<int,int> m2(m);
// 赋值
map<int,int> m3;
m3 = m2;
}
int main()
{
test01();
system("pause");
return 0;
}
运行结果:
3.9.3 map大小和交换
函数原型:
empty(); //判断容器是否为空
size(); // 返回容器中元素的数目
swap(mp); // 交换两个集合容器
3.9.4 map插入和删除
函数原型:
insert(elem); // 插入元素,注意是对组
clear(); // 清空
erase(pos);
erase(beg,end);
erase(key); // 按照key值删除
示例:
#include<iostream>
using namespace std;
#include<map>
void printMap(const map<int,int> &m)
{
for(map<int,int>::const_iterator it = m.begin();it!=m.end();it++)
{
cout << it->first << " " << it->second << endl;
}
}
void test01()
{
map<int,int> m;
// 插入--- 四种方法
m.insert(pair<int,int>(1,10));
m.insert(make_pair(2,20));
m.insert(map<int,int>::value_type(3,30));
m[4] = 40;
// 不建议用于插入数据,主要用于通过key访问value
cout << m[5] << endl;
// key为5不存在,就会自动在容器中创建一个key为5,value为0的元素
cout << m[1] << endl;
printMap(m);
// 删除
cout << "删除后:" << endl;
m.erase(m.begin());
m.erase(4); // 按照key值删除
printMap(m);
}
int main()
{
test01();
system("pause");
return 0;
}
运行结果:
3.9.5 map查找和统计
根据key值进行查找和统计
函数原型:
find(key); // 查找key值是否存在,存在返回该键的元素的迭代器,不存在返回map.end()
count(key); // 统计key的元素个数
找了一圈没找到,就返回最后的位置。根据返回值是否为map.end()
,判断是否找到元素。
3.9.6 map排序
默认排序是升序,利用仿函数,就可以将其改为降序。
示例:
#include<iostream>
using namespace std;
#include<map>
class myCmp
{
public:
bool operator()(int v1,int v2)
{
return v1 > v2;
}
};
void test01()
{
map<int,int,myCmp> m;
m.insert(make_pair(1,10));
m.insert(make_pair(2,20));
m.insert(make_pair(3,30));
m.insert(make_pair(4,40));
for(map<int,int,myCmp>::iterator it = m.begin();it!=m.end();it++)
{
cout << it->first << " " << it->second << endl;
}
}
int main()
{
test01();
system("pause");
return 0;
}
运行结果: