1.map的本质是一类关联容器,其Key不可以修改,map的内部实现是一颗红黑树,因此其内部的数据都是有序的。
2.
- map的功能是自动建立Key-value的意义对应的关系,值得注意的是key的类型必须支持<操作符
- 根据key值可以快速的查找记录,其复杂度为log(N)
3.往map中插入元素
- myMap.insert(pair<int, string>(1, "first"));
- myMap.insert(map<int, string>::value_type(2, "second"));
- myMap[1] = "first_"; //与上不同的是其可以覆盖key对应的value
4.insert的返回值是一个pair类型
pair<map<int, string>::iterator,bool>rMap=myMap.insert(map<int, string>::value_type(1, "first__"));
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
//创建一个map,以三种方式进行插入数据
map<int, string>myMap;
myMap.insert(pair<int, string>(1, "first"));
myMap.insert(map<int, string>::value_type(2, "second"));
myMap[1] = "first_";
//insert的返回值
pair<map<int, string>::iterator,bool>rMap=myMap.insert(map<int, string>::value_type(1, "first__"));
cout << "insert operation:" <<boolalpha<< rMap.second << endl;
//循环输出map
cout << "myMap:" << endl;
for (map<int, string>::iterator it = myMap.begin(); it != myMap.end(); it++) {
cout << "Key:" << (*it).first << " Value:" << (*it).second << endl;
}
}
5.erase
注意erase函数
for(map<int,int>::iterator it = mapInt.begin(); it != mapInt.end();)
{
if(it->second == 0)
{
mapInt.erase(it++);//涉及到后缀++其实返回的是一个it的副本
}
else
{
it++;
}
}
6.重定义map内部的Compare函数
#include <iostream>
#include <map>
#include <string>
using namespace std;
struct cmpString {
bool operator()(const string& s1, const string& s2) {
return s1.length() < s2.length();
}
};
int main()
{
map<string, int, cmpString>myMap;
myMap.insert(pair<string,int >("ZiLinMi", 72));
myMap.insert(pair<string, int >("Bob", 79));
myMap.insert(pair<string, int >("LiMin", 90));
//循环输出map
cout << "myMap:" << endl;
for (map<string, int, cmpString>::iterator it = myMap.begin(); it != myMap.end(); it++) {
cout << "Key:" << (*it).first << " Value:" << (*it).second << endl;
}
}