STL学习笔记5--map and multimap

Maps是一种关联式容器,包含“关键字/值”对。 Multimaps和maps很相似,但是MultiMaps允许重复的元素。

  简单介绍:

1、声明,首先包含头文件 “map”

    map <int,string> test1,test2;//
    map <int,string>::iterator it1,it2;//迭代器
    multimap <int,string> test3;
    multimap <int,string>::iterator it3;

 

2、插入数据,可使用三种方法:

  第一种,使用pair函数

   test1.insert(pair<int,string>(1,"song"));
    test1.insert(pair<int,string>(2,"zhang"));
    test1.insert(pair<int,string>(3,"wang"));

  第二种,使用value_type类型

   test1.insert(map<int,string>::value_type(4,"qian"));
    test1.insert(map<int,string>::value_type(5,"sun"));

  第三种,使用数组方式,,可以覆盖原来数据,前两中不能改变数据,如果存在则插入失败

    test1[6] = "mao";
    test1[7] = "guang";

  前两种情况,插入失败后可以通过以下方法检查

复制代码
//测试是否插入成功
    pair<map<int,string>::iterator,bool> insert_Pair;
    insert_Pair = test1.insert(pair<int,string>(1,"Replace"));
    if (insert_Pair.second == true)
    {
        cout<<"insert successfully"<<endl;
    }
    else
    {
        cout<<"insert failure"<<endl;
    }
复制代码

3、遍历数据,可使用以下几种方法

  第一,正向遍历

    for (it1 = test1.begin();it1 != test1.end();it1++)
    {
        cout<<it1->first<<"-----" << it1->second<<endl;
    }

  第二,逆向遍历,使用反向迭代器

  cout<<"反向迭代器"<<endl;
    //rbegin()指向最后一个元素,rend()指向第一个元素前面,这里++是指往前走一个位置
    map<int,string>::reverse_iterator reverseIte;
    for (reverseIte = test1.rbegin();reverseIte != test1.rend();reverseIte++)
    {
        cout<<reverseIte->first<<"-----" << reverseIte->second<<endl;
    }

  第三,使用数组进行遍历

  //使用数组方式进行遍历
    for (int i = 1;i <= test1.size();i++)
    {
        cout<<i<<"-----"<<test1[i]<<endl;
    }

4、查找和判断

  第一,使用count进行判断

复制代码
    //count,判断
    int i=1;
    for (it1 = test1.begin();it1 != test1.end();i++,it1++)
    {
        cout<<i;
        if (test1.count(i)>0)//元素存在
        {
            cout<<"is a element of map"<<endl;
        }
        else
        {
            cout<<"is not a element of map"<<endl;
        }
    }
复制代码

  第二,使用find判断

复制代码
  it2 = test1.find(6);//查找
    if (it2 != test1.end())
    {
        cout<<"find it:"<<it2->first<<"---"<<it2->second<<endl;
    }
    else
    {
        cout<<"not find it"<<endl;
    }
复制代码

5、删除元素

    //删除元素
    it2  = test1.find(2);
    test1.erase(it2);

 

 

这些操作基本上都和set的差不多,好多函数一模一样。

  

posted @   struggle_time  阅读(362)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示