博客
关于我
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/

    你可能感兴趣的文章
    PAT (Basic Level) Practice 乙级1051-1055
    查看>>
    PAT (Basic Level) Practise - 写出这个数
    查看>>
    PAT 1027 Colors in Mars
    查看>>
    PAT 1127 ZigZagging on a Tree[难]
    查看>>
    PAT 2-07. 素因子分解(20)
    查看>>
    PAT A1033 重点题
    查看>>
    SparkSQL学习03-数据读取与存储
    查看>>
    PAT L2-012. 关于堆的判断
    查看>>
    PAT Spell It Right [非常简单]
    查看>>
    PAT-1044. Shopping in Mars (25)
    查看>>
    PAT-乙级-1040 有几个PAT
    查看>>
    pat1011. World Cup Betting (20)
    查看>>
    Spring组件扫描配置
    查看>>
    PAT1093 Count PAT's (25)(逻辑题)
    查看>>
    PATA1038题解(需复习)
    查看>>
    Patching Array
    查看>>
    Spring源码学习(二):Spring容器之prepareContext和BeanFactoryPostProcessor的介绍
    查看>>
    PatchMatchStereo可能会需要的Rectification
    查看>>
    Path does not chain with any of the trust anchors
    查看>>
    Path形状获取字符串型变量数据
    查看>>