STL map:
内部数据结构:运用红黑树,删除增加节点对其它节点没有影响,迭代器可以修改实值,不可修改key,搜索的时间复杂度未log2(n)
map的功能:
快速插入key-value记录
快速删除记录
根据key修改value
遍历所有记录
使用举例:
//noting : the key of map should define “<”
//注意:map用到的结构体需要重定义"<"运算符
#include<map>
struct axis
{
int x;
int y;
//noting : the key of map should define "<"
bool operator < (const struct axis o) const
{
if( x != o.x)
return x>o.x;
else
return y>o.y;
}
};
map<int, string> mapStudent;
mapStudent[3] = “student_three”;//有key键可覆盖
mapStudent.insert(pair<int, string>(3, “student_three”));//有key键不可插入
pair<map<int, string>::iterator, bool> Insert_Pair;
Insert_Pair = mapStudent.insert(pair<int, string>(1, “student_one”));//其中Insert_Pair.second返回true代表插入成功 map<int, string>::iterator iter;
//迭代器遍历输出
for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout<first<<’ '<second<<endl;
//逆向迭代
for(iter = mapStudent.rbegin(); iter != mapStudent.rend(); iter++)
cout<first<<" "<second<<endl;
iter = mapStudent.find(1);//查找
if(iter != mapStudent.end())
cout<<"Find, the value is "<second<<endl;
else
cout<<“Do not Find”<<endl;
mapStudent.erase(iter);//删除
//STL中默认是采用小于号来排序