C++ STL的map是一个基于红黑树的容器类,查找和删除的效率都是O(logn),这是一个通过空间消耗获得时间效率的典型模式。通过具体的例子来看下这个容器类的插入,删除和查询操作。
#include<iostream>
#include<map>
#include<string>
using namespace std;
void mapExample()
{
/*插入操作*/
map<int, string> mapTest; //声明一个名为mapTest的map容器对象
mapTest.insert(pair<int, string>(1, "world"));
mapTest.insert(pair<int, string>(2, "peace")); //map插入操作
mapTest[0] = "My wish is"; //以数组的方式插入元素
map<int, string>::iterator ite; //声明一个map<int,string>的内容迭代器
for (ite = mapTest.begin(); ite != mapTest.end(); ite++) //map遍历
{
cout << ite->first << "," << ite->second << endl;
}
/*我们测试一下第二次插入相同的key值,是否能插入成功*/
pair<map<int, string>::iterator, bool> result;
result = mapTest.insert(pair<int, string>(1, "I am a chengXuYuan"));
cout << "the result is: " << result.second << endl; //为0则表示失败,为1则表示成功
/*删除操作*/
int n = mapTest.erase(1);//删除key=1的元素
cout << n << endl;
for (ite = mapTest.begin(); ite != mapTest.end(); ite++)
{
cout << ite->first << "," << ite->second << endl;
}
}
int main()
{
mapExample();
return 0;
}