本文为博主原创文章,未经博主允许不得转载。
https://blog.csdn.net/lxy_2011/article/details/52712056
一、今日课题
map
二、实战演练
map是一类关联式容器,它是模板类。关联的本质在于元素的值与某个特定的键相关联,而并非通过元素在数组中的位置类获取。它的特点是增加和删除节点对迭代器的影响很小,除了操作节点,对其他的节点都没有什么影响。对于迭代器来说,不可以修改键值,只能修改其对应的实值。
1)有何用?
Vectors 包含着一系列连续存储的元素,其行为和数组类似。访问Vector中的任意元素或从末尾添加元素都可以在常量级时间复杂度内完成,而查找特定值的元素所处的位置或是在Vector中插入元素则是线性时间复杂度。
2)怎么用?
自动建立Key - value的对应。key 和 value可以是任意你需要的类型,但是需要注意的是对于key的类型,唯一的约束就是必须支持<操作符。
根据key值快速查找记录,查找的复杂度基本是Log(N),如果有1000个记录,最多查找10次,1,000,000个记录,最多查找20次。
快速插入删除
代码示例:
#include <iostream>
#include <string>
#include<map>
using namespace std;
int main()
{
map<const char*, int > m;
m["a"] = 1;
m["b"] = 6;
m["c"] = 9;
map<const char*, int>::iterator it;
it = m.begin();
const char* c = it->first;
cout << "first element is :" << c << endl;
int i = m["c"];
while (it != m.end())
{
cout << it->first << ";" << it->second << endl;
++it;
}
cout << "m[\"c\"]=" << i << endl;
cout << "sizeof m:" << m.size() << endl;
cout << "erase m[\"c\"](1:succ 0:failed):" << m.erase("c") << endl;
cout << "erase m[\"c\"]:" << m.erase("c") << endl;
cout << "sizeof m:" << m.size() << endl;
cout << "m[c]=" << m["c"] << endl;
cout << "sizeof m :" << m.size() << endl;
system("pause");
return 0;
}
3)Access & Operations