博客
关于我
c++标准库中的关联容器
阅读量:271 次
发布时间:2019-03-01

本文共 1178 字,大约阅读时间需要 3 分钟。

C++标准库中有序和无序的容器

C++标准库中提供了多种容器,用于存储键值对或单一键的数据。这些容器可以根据键的存储顺序分为有序和无序两种类型。

有序的容器包括:

  • map:用于存储键值对(key: value),并且键是按一定顺序排列的。
  • set:用于存储单一键,键是按一定顺序排列的。
  • multimap:与map类似,但允许键的重复出现。
  • multiset:与set类似,但允许键的重复出现。
  • 无序的容器包括:

  • unordered_map:与map类似,但键是无序存储的。
  • unordered_set:与set类似,但键是无序存储的。
  • unordered_multimap:与multimap类似,但键是无序存储的。
  • unordered_multiset:与multiset类似,但键是无序存储的。
  • 默认分配器的设置

    • map的默认分配器是std::allocator<std::pair<const K, V>>
    • set的默认分配器是std::allocator<K>

    主要操作

  • 添加元素

    • map需要使用std::pair类型来添加元素。例如:
    std::map
    map2;map2.insert(std::make_pair(2, "xxx"));

    或者可以使用括号初始化的方式:

    map2.insert({4, "xxxx"});
  • 遍历元素

    • 使用迭代器来遍历元素。例如:
    std::map
    map2;map2.insert(std::make_pair(2, 6.66));map2.insert({4, 8.88});for (auto it = map2.begin(); it != map2.end(); ++it) { qDebug() << it->first << it->second;}
  • 删除元素

    • 使用erase()方法删除元素。例如:
    std::map
    map2;map2.insert(std::make_pair("www", 6.66));map2.insert({"qqqqq", 8.88});// 遍历并打印元素for (auto it = map2.begin(); it != map2.end(); ++it) { qDebug() << it->first << it->second;}map2.erase("www");// 再次遍历打印元素for (auto it = map2.begin(); it != map2.end(); ++it) { qDebug() << it->first << it->second;}
  • 这些容器在实际应用中广泛使用,适用于根据键进行快速查找和排序操作的场景。

    转载地址:http://tavx.baihongyu.com/

    你可能感兴趣的文章
    Oracle:ORA-00911: 无效字符
    查看>>
    Text-to-Image with Diffusion models的巅峰之作:深入解读 DALL·E 2
    查看>>
    Tensorflow.python.framework.errors_impl.ResourceExhaustedError:无法分配内存[操作:AddV2]
    查看>>
    TCP基本入门-简单认识一下什么是TCP
    查看>>
    tableviewcell 中使用autolayout自适应高度
    查看>>
    Symbolic Aggregate approXimation(SAX,符号聚合近似)介绍-ChatGPT4o作答
    查看>>
    Orcale表被锁
    查看>>
    svn访问报错500
    查看>>
    sum(a.YYSR) over (partition by a.hy_dm) 不需要像group by那样需要分组函数。方便。
    查看>>
    ORCHARD 是什么?
    查看>>
    Struts2中使用Session的两种方法
    查看>>
    Stream API:filter、map和flatMap 的用法
    查看>>
    STM32工作笔记0032---编写跑马灯实验---寄存器版本
    查看>>
    order by rand()
    查看>>
    SSM(Spring+SpringMvc+Mybatis)整合开发笔记
    查看>>
    Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
    查看>>
    org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
    查看>>
    sql查询中 查询字段数据类型 int 与 String 出现问题
    查看>>
    org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
    查看>>
    org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
    查看>>