简介:
1.map中所有的元素都是pair
2.pair中第一个元素为key(键值),起到索引作用,第二个元素为value(实值),知道Python字典的可以联系理解一下
3.所有元素都会根据元素键值自动排序
本质:
map/multimap属于关联式容器,底层结构用二叉树实现
优点:可以根据key值快速找到value值
map和multimap的区别:
1.map不允许容器中有重复key元素
2.multimap允许容器中有重复key元素(注意是key,value是可以重复的)
map遍历
void printmap(map<int,int>m) {
for (map<int, int>::iterator it = m.begin(); it != m.end(); it++) {
//这里访问key和value通过位置.first和.second来访问
cout << "key = " << (*it).first << "\nvalue = " << it->second << endl;//两种写法等效
}
}
一.map构造和赋值
map<T1,T2>mp;//map默认构造
map(const map &mp);//拷贝构造
赋值:map& operator=(const map &mp);//重载等号,用的时候直接用等号连接就行
void test() {
//创建容器
map<int, int>m;
m.insert(pair<int, int>(1, 10));//1起到索引的作用,10作为value
m.insert(pair<int, int>(2, 20));
m.insert(pair<int, int>(3, 30));
m.insert(pair<int, int>(4, 40));
printmap(m);
//拷贝构造
map<int, int>m2(m);
//赋值直接用等号连接,不写了
}
二.大小和交换
size();//返回容器中元素的数目
empty();//判断容器是否为空
swap();//交换两个集合容器
代码略
三.插入和删除
这里在插入时要用到pair
insert(pair<T1,T2>(num1,num2));//
insert(elem);//在容器中插入元素
clear();//清除所有元素
erase(pos);//删除pos迭代器所指的元素,返回下一个元素的迭代器
erase(beg,end);//删除区间[beg,end)的所有元素,返回下一个元素的迭代器
erase(key);//删除容器中值为key的元素
void test() {
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
printmap(m);
cout << m[5] << endl;//会自动创建一个默认值为0的value,会创建心得对象
//删除
m.erase(m.begin());
printmap(m);//第一个被删除
m.erase(3);//用key来删除
//清空
//m.erase(m.begin(), m.end());
m.clear();
printmap(m);//已清空
}
四.查找和统计
函数原型:
find(key);//查找可以是否存在,若存在,返回键的元素的迭代器;若不存在返回set.end();
count(key);//统计key的元素个数
void test() {
map<int, int>m;
m.insert(pair<int, int>(1, 10));
m.insert(pair<int, int>(2, 20));
m.insert(pair<int, int>(3, 30));
m.insert(pair<int, int>(4, 40));
map<int, int>::iterator pos = m.find(3);
if (pos != m.end()) {
cout << "查到了元素key = " << (*pos).first << " value = " << pos->second << endl;
}
else {
cout << "未找到元素" << endl;
}
//统计
//map不允许插入重复的元素,所以count统计要么是1要么是0
//multimap可以大于1
int num = m.count(3);
cout << "num = " << num << endl;
}
五.排序
默认是从小到大排序,利用仿函数实现从大到小排序
class Mycompare {
public:
bool operator()(int v1, int v2)const {
//降序
return v1 > v2;
//升序
//return v1 < v2;
}
};
void test() {
map<int, int,Mycompare>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));
m.insert(make_pair(5, 50));
for (map<int, int, Mycompare>::iterator it = m.begin(); it != m.end(); it++) {
cout << "key = " << it->first << "value = " << it->second << endl;
}
}