map的介绍
标准的STL关联程序(set,map,multset,multmap)的内部结构是平衡二叉树。平衡二叉树分为:avl-tree,rb-tree,aa-tree。
STL的底层机制都是以RB-tree(红黑树)实现的。RB-tree是一个不被外界使用的容器。所以map的底层是以红黑树实现的,注意和hashmap的区分。map底层是红黑树,hashmap底层是hash表。
之前在高效的读取一个文件中指定行号的内容的时候也用到了map中的方法:
完整的示例程序,主要是对容器map中的元素,进行插入,删除和遍历的操作。
#include "stdafx.h"
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
map<int, string> map_str;//
map_str.insert(pair<int, string>(5, "orange"));//map中存放的是pair<int,string>类型的元素
map_str.insert(pair<int, string>(1, "banana"));
map_str.insert(pair<int,string>(2,"peach"));
map_str.insert(pair<int, string>(4, "peanut"));
map_str.insert(pair<int, string>(3,"apple"));
map_str.insert(pair<int,string>(4,"grape"));//这里插入失败,因为前面已经有key为4的元素
/*以下开始使用迭代器遍历map容器中的内容*/
std::cout << "1:int" << endl;
map<int, string>::iterator it = map_str.begin();
while (it != map_str.end())
{
std::cout << (*it).first << ":" << (*it).second << endl;
it++;
}
map_str[2] = "mango";//这里会覆盖之前key为2的值
map_str[6] = "mangosteen";//map容器中刚好没有key为6的元素,直接添加到后面
std::cout << "2:add key=6 and modify key=2" << endl;
it = map_str.begin();
while (it != map_str.end())
{
std::cout << (*it).first << ":" << (*it).second << endl;
it++;
}
/*以下为随机访问其中一个元素的方法*/
it = map_str.find(4);
std::cout << "3:find key=4" << endl;
std::cout << (*it).first << ":" << (*it).second << endl;
/*删除中元素的方法*/
map_str.erase(4);//删除key=4的元素
std::cout << "4:delete key =4"<<endl;
it = map_str.begin();
while (it != map_str.end())
{
std::cout << (*it).first << ":" << (*it).second << endl;
it++;
}
it = map_str.find(5);//查找key=5的元素
if (it != map_str.end())//判断是否查找成功
{
map_str.erase(it);//删除key=5的元素
}
std::cout << "5:find key=5 and delete key=5" << endl;
it = map_str.begin();
while (it != map_str.end())
{
std::cout << (*it).first << ":" << (*it).second << endl;
it++;
}
return 0;
}