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

    你可能感兴趣的文章
    nodejs + socket.io 同时使用http 和 https
    查看>>
    NodeJS @kubernetes/client-node连接到kubernetes集群的方法
    查看>>
    Nodejs express 获取url参数,post参数的三种方式
    查看>>
    nodejs http小爬虫
    查看>>
    nodejs libararies
    查看>>
    nodejs npm常用命令
    查看>>
    Nodejs process.nextTick() 使用详解
    查看>>
    NodeJS 导入导出模块的方法( 代码演示 )
    查看>>
    nodejs 的 Buffer 详解
    查看>>
    nodejs 读取xlsx文件内容
    查看>>
    nodejs 运行CMD命令
    查看>>
    nodejs+nginx获取真实ip
    查看>>
    nodejs-mime类型
    查看>>
    NodeJs——(11)控制权转移next
    查看>>
    NodeJS、NPM安装配置步骤(windows版本)
    查看>>
    NodeJS、NPM安装配置步骤(windows版本)
    查看>>
    nodejs与javascript中的aes加密
    查看>>
    nodejs中Express 路由统一设置缓存的小技巧
    查看>>
    Nodejs中的fs模块的使用
    查看>>
    nodejs包管理工具对比:npm、Yarn、cnpm、npx
    查看>>