• STL中的map


    一。用数组来插入会覆盖:

      mapStudent[1] =  “student_one”;

      mapStudent[1] =  “student_two”;

    顺序执行后结果是: mapStudent[1] ==  “student_two”(覆盖了)。

    二。我们怎么知道当前已经插入了多少数据呢,可以用size函数


    三。用count函数来判定关键字(即中括号里的键)是否出现,count函数的返回值只有两个,要么是0,要么是1


    四。用find函数来定位数据出现位置,它返回的一个迭代器,当数据出现时,它返回数据所在位置的迭代器,如果map中没有要查找的数据,它返回的迭代器等于end函数返回的迭代器

    View Code
    #include <map>

    #include <string>

    #include <iostream>

    using namespace std;

    Int main()

    {

    map<int, string> mapStudent;

    mapStudent.insert(pair<int, string>(1, "student_one"));

    mapStudent.insert(pair<int, string>(2, "student_two"));

    mapStudent.insert(pair<int, string>(3, "student_three"));

    map<int, string>::iterator iter;

    iter = mapStudent.find(1);

    if(iter != mapStudent.end())

    {

    cout<<"Find, the value is "<< iter->second <<endl;

    }

    else

    {

    cout<<"Do not Find"<<endl;

    }
    return 0;

    }



    五。   数据的清空与判空

    清空map中的数据可以用clear()函数,判定map中是否有数据可以用empty()函数,它返回true则说明是空map

    六。  数据的删除

    这里要用到erase函数,它有三个重载了的函数,下面在例子中详细说明它们的用法

    Int main()

    {

           Map<int, string> mapStudent;

           mapStudent.insert(pair<int, string>(1, “student_one”));

           mapStudent.insert(pair<int, string>(2, “student_two”));

           mapStudent.insert(pair<int, string>(3, “student_three”));

    //如果你要演示输出效果,请选择以下的一种,你看到的效果会比较好

           //如果要删除1,用迭代器删除

           map<int, string>::iterator iter;

           iter = mapStudent.find(1);

           mapStudent.erase(iter);

           //如果要删除1,用关键字删除

           Int n = mapStudent.erase(1);//如果删除了会返回1,否则返回0

           //用迭代器,成片的删除

           //一下代码把整个map清空

           mapStudent.earse(mapStudent.begin(), mapStudent.end());

           //成片删除要注意的是,也是STL的特性,删除区间是一个前闭后开的集合

           //自个加上遍历代码,打印输出吧

    }



  • 相关阅读:
    反射之初认识
    面向对象(上)练习一 改进:调用方法
    关于php中id设置自增后不连续的问题
    由于定界符引出的格式错误问题
    PHP 关于timezone问题
    2016.4.29 园子第一天,希望所有的坚持都有所收获
    递归调用
    动手动脑
    界面实验任务
    课程作业02
  • 原文地址:https://www.cnblogs.com/qiufeihai/p/2405101.html
Copyright © 2020-2023  润新知