zoukankan      html  css  js  c++  java
  • c++ Map使用

    引入头文件:

    #include <map>
    1、初始化
    map<int, int> a, b;
    map<sting, int> a, b;
    2、添加数据
    map<int ,string> maplive;
    法一:maplive.insert(pair<int,string>(102,"aclive"));
    法二:maplive[112]="April";//map中最简单最常用的插入添加!
    3、查找数据
    find()函数返回一个迭代器指向键值key的元素,如果没找到返回尾部的迭代器。

    map<int ,string> maplive;
    map<int ,string >::iterator result;
    result=maplive.find(112);
    if(l_it==maplive.end())
    cout<<"we do not find 112"<<endl;
    else cout<<"wo find 112"<<endl;

    对于迭代器 result
    result->first //存储键值key
    result->second //存储数据value
    4、删除数据

    map<int ,string> maplive;
    map<int ,string >::iterator result;
    result=maplive.find(112);
    if(result==maplive.end())
    cout<<"we do not find 112"<<endl;
    else maplive.erase(result); //delete 112;map的erase()函数的形参是迭代器。

    如果全部删除 maplive.clear()
    5、遍历数据

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

    6、排序
    Map中的元素是自动按key升序排序,所以不能对map用sort函数:

    7、map的基本操作函数:
    C++ Maps是一种关联式容器,包含“关键字/值”对
    begin() 返回指向map头部的迭代器
    clear() 删除所有元素
    count() 返回指定元素出现的次数,其中形参是key值
    empty() 如果map为空则返回true
    end() 返回指向map末尾的迭代器
    erase() 删除一个元素
    find() 查找一个元素
    insert() 插入元素
    key_comp() 返回比较元素key的函数
    value_comp() 返回比较元素value的函数
    lower_bound() 返回键值>=给定元素的第一个位置(返回结果为迭代器)(形参是key值)
    upper_bound() 返回键值>给定元素的第一个位置(返回结果为迭代器)(形参是key值)
    max_size() 返回可以容纳的最大元素个数
    size() 返回map中元素的个数
    swap() 交换两个map

  • 相关阅读:
    win10 彻底删除mysql步骤
    IDEA中添加类的创建者信息
    针对标签中设置 disabled="true",$("#id").serialize()获取不到value的解决方法
    使用Vue-cli创建project遇到的坑
    Jmeter压测总结
    Java通过ssh远程连接服务器
    Django 学习笔记(一)
    Python 测试框架基础
    Python 基础&Excel操作
    Appium环境搭建及计算器小实验
  • 原文地址:https://www.cnblogs.com/likailiche/p/4897069.html
Copyright © 2011-2022 走看看