zoukankan      html  css  js  c++  java
  • STL之map&multimap使用简介

    map

    1.insert

    第一种:用insert函数插入pair数据
    #include <map>
    #include <string>
    #include <iostream>
    using namespace std;
    int main()
    {
           map<int, string> map;
           map.insert(pair<int, string>(1, “one”));
           map.insert(pair<int, string>(2, “two”));
           map.insert(pair<int, string>(3, “three”));
           map<int, string>::iterator  iter;
           for(iter = map.begin(); iter != map.end(); iter++)
            {
              cout<<iter->first<<”   ”<<iter->second<<end;
            }
    }    
    第二种:用insert函数插入value_type数据
    #include <map>
    #include <string>
    #include <iostream>
    using namespace std;
    int main()
    {
           map<int, string> map;
           map.insert(map<int, string>::value_type (1, “one”));
           map.insert(map<int, string>::value_type (2, “two”));
           map.insert(map<int, string>::value_type (3, “three”));
           map<int, string>::iterator  iter;
           for(iter = map.begin(); iter != map.end(); iter++)
            {
              cout<<iter->first<<”   ”<<iter->second<<end;
            }
    }   
    第三种:用数组方式插入数据
    #include <map>
    #include <string>
    #include <iostream>
    using namespace std;
    int main()
    {
           map<int, string> map;
           map[1]=“one”;
           map[2]=“two”;
           map[3]= “three”;
           map<int, string>::iterator  iter;
           for(iter = map.begin(); iter != map.end(); iter++)
            {
              cout<<iter->first<<”   ”<<iter->second<<end;
            }
    }   

    map 总是以(key,value)的形式存在,当插入的数据的key已经存在时,会形成覆盖,map内部使用红黑树实现。

    2.size
    返回map的大小
     
    3.遍历
      可以使用迭代器方式,如1中的例子
      也可以使用[],但是注意索引从1开始
     
    #include <map>
    #include <string>
    #include <iostream>
    using namespace std;
    int main()
    {
           map<int, string> map;
           map.insert(pair<int, string>(1, “one”));
           map.insert(pair<int, string>(2, “two”));
           map.insert(pair<int, string>(3, “three”));
           for(int index=1;index<=map.size();index++)
            {
              cout<<map[index]<<endl;
            }
    }    

    4.查找

    map.find()如果查找到,返回指向结果的迭代器,如果没有找到到,返回map.end()

    5.上下界

    lower_bound函数用法,这个函数用来返回要查找关键字的下界(是一个迭代器),返回键值>=给定元素的第一个位置
    upper_bound函数用法,这个函数用来返回要查找关键字的上界(是一个迭代器),返回键值>给定元素的第一个位置

    6.清空与判空

    清空map中的数据可以用clear()函数,判定map中是否有数据可以用empty()函数,它返回true则说明是空map
     
    multimap和map的区别在于,multimap允许key重复,其他没啥特别的地方,底层也是红黑树实现
  • 相关阅读:
    Oracle 语法中的 INSERT INTO
    [Oracle]高效的SQL语句之分析函数(一)sum()
    Oracle:trunc()函数简介
    ORACLE 调试输出,字符串执行函数
    Oracle 的几种循环方式介绍
    js 判断字符串是否存在某个字符串
    IntelliJ IDEA 2021.3 旗舰版 官方中文正式版(附汉化包+安装教程)
    主线程中同步的 XMLHttpRequest 已不推荐使用,因其对终端用户的用户体验存在负面影响。可访问 http://xhr.spec.whatwg.org/ 详细了解
    js杂记:x:function(){}
    ORACLE 两表关联更新三种方式
  • 原文地址:https://www.cnblogs.com/tla001/p/6642790.html
Copyright © 2011-2022 走看看