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;
}