zoukankan      html  css  js  c++  java
  • C++:标准模板库map

    一:介绍

    map是STL的关联式容器,以key-value的形式存储,以红黑树(平衡二叉查找树)作为底层数据结构,对数据有自动排序的功能。

    命名空间为std,所属头文件<map> 注意:不是<map.h>

    二:常用操作

    容量:
    a.map中实际数据的数据:map.size()
    b.map中最大数据的数量:map.max_size()
    c.判断容器是否为空:map.empty()

    修改:
    a.插入数据:map.insert()
    b.清空map元素:map.clear()
    c.删除指定元素:map.erase(it)

    迭代器:
    a.map开始指针:map.begin()
    b.map尾部指针:map.end() 注:最后一个元素的下一个位置,类似为NULL,不是容器的最后一个元素

    三:存储

        map<int, string> map1;
    
        //方法1:
        map1.insert(pair<int, string>(2, "beijing"));
        //方法2:
        map1[4] = "changping";
        //方法3:
        map1.insert(map<int, string>::value_type(1, "huilongguan"));
        //方法4:
        map1.insert(make_pair<int, string>(3, "xierqi"));

    四:遍历

    	for (map<int, string>::iterator it=map1.begin(); it!=map1.end(); it++)
    	{
    		cout << it->first << ":" << it->second << endl;
    	}

    五:查找

    	string value1 = map1[2];
    	if (value1.empty())
    	{
    		cout << "not found" << endl;
    	}
    
    	//方法2
    	map<int, string>::iterator it = map1.find(2);
    	if (it == map1.end())
    	{
    		cout << "not found" << endl;
    	}
    	else
    	{
    		cout << it->first << ":" << it->second << endl;
    	}

    六:修改

    	//修改数据
    	map1[2] = "tianjin";

    七:删除

    	//方法1
    	map1.erase(1);
    
    	//方法2
    	map<int, string>::iterator it1 = map1.find(2);
    	map1.erase(it1);

    欢迎加群交流:C/C++开发交流

  • 相关阅读:
    OBJ文件格式详解
    HashMap的用法
    HashMap和Hashtable的区别
    加载物体的方法
    drawSelf(int texId)格式对应
    adb.exe诊断
    Android Eclipse如何用BlueStacks模拟器
    .md5mesh and .md5anim文件介绍
    ubuntu命令行下中文乱码的解决方案 (我采取了其中方案一与方案二,都还没成功—待定)
    Ubuntu下小巧智能的代码编辑器Scribes
  • 原文地址:https://www.cnblogs.com/woniu201/p/11694612.html
Copyright © 2011-2022 走看看