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

    你可能感兴趣的文章
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    nnU-Net 终极指南
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>