C++ map基本操作实例
2017-09-07 11:31
471 查看
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; }
相关文章推荐
- C++map的基本操作和使用
- C++ map的基本操作和使用
- C++ map的基本操作和用法
- C++ map的基本操作和使用
- C++ map的基本操作和使用
- C++ map的基本操作和使用
- C++ map的基本操作和使用
- C++ map的基本操作和使用
- C/C++基础——map的基本操作总结
- C++ map的基本操作和使用
- C++ map基本操作
- C++ map的基本操作和使用
- C++ map的基本操作和使用
- 【C++ map 的基本使用和操作】
- 数据结构之队列的基本操作入队出队初始化删除-c++代码实现及运行实例结果
- C++ map的基本操作和使用
- C++—map的基本操作总结
- 【编程语言】C++--map的基本操作和使用
- c++map基本操作
- C++ map的基本操作和使用