当前位置: 首页 > news >正文

三种容器 std::vector、std::map、std::unordered_set 的对比分析

目录

1.添加元素

1.1 std::vector

1.2 std::map

1.3 std::unordered_set

2. 查找元素

2.1 std::vector

2.2 std::map

2.3 std::unordered_set

3. 遍历容器

3.1 std::vector

使用范围基for循环(range-based for loop)

使用迭代器:

3.2 std::map

3.3 std::unordered_set

4.删除元素

4.1 std::vector

4.2 std::map

4.3 std::unordered_set

5. 综合分析

6.优缺点对比

示例代码片段

7. 总结


在C++编程中,选择合适的容器对于代码的性能和功能至关重要。本文将对比分析 std::vectorstd::map 和 std::unordered_set 这三种常用容器的使用方式、特点,特别是在添加元素、查找元素和遍历容器等方面的表现。

1.添加元素

1.1 std::vector

std::vector 是一个动态数组,支持快速随机访问,但在插入或删除元素时,可能需要移动大量数据。

std::vector<std::pair<int, int>> problems;  
problems.emplace_back(std::pair<int, int>(randomValue1, randomValue2));

1.2 std::map

std::map 是一种平衡二叉搜索树(红黑树)实现的有序关联容器,插入操作的时间复杂度为 O(log n),且自动按键排序。

std::map<std::string, int> incorrectProblems;  
incorrectProblems.insert(std::pair<std::string, int>(exp, result.second));

1.3 std::unordered_set

std::unordered_set 是基于哈希表的无序关联容器,插入操作的平均时间复杂度为 O(1),但在最坏情况下可能退化为 O(n)。

std::unordered_set<std::string> uniqueProblems;  
uniqueProblems.insert(exp);

2. 查找元素

2.1 std::vector

在 std::vector 中查找元素通常需要线性搜索,时间复杂度为 O(n),但如果数据有序,可以使用二分查找优化。

auto it = std::find_if(problems.begin(), problems.end(),   [=](const auto& problem) {   return problem.first == value1 && problem.second == value2;   });

2.2 std::map

std::map 使用平衡二叉树结构,查找操作的时间复杂度为 O(log n),且支持按键直接访问。

auto it = incorrectProblems.find(exp);  
if (it != incorrectProblems.end()) {  // 元素存在  
}

2.3 std::unordered_set

std::unordered_set 基于哈希表实现,查找操作的平均时间复杂度为 O(1)。

if (uniqueProblems.find(exp) != uniqueProblems.end()) {  // 元素存在  
}

http://www.mrgr.cn/news/54865.html

相关文章:

  • 7、Nodes.js包管理工具
  • Vue 3集成海康Web插件实现视频监控
  • 今日头条躺赚流量:自动化新闻爬取和改写脚本
  • IDEA如何查看所有的断点(Breakpoints)并关闭
  • 深度解析模型调优与正则化:L1、L2正则化及偏差-方差的权衡
  • <项目代码>YOLOv8路面病害识别<目标检测>
  • 【热门主题】000004 案例 Vue.js组件开发
  • C++算法练习-day11——242.有效的字母异位词
  • CSS网页布局(重塑网页布局)
  • (A-D)AtCoder Beginner Contest 376
  • es的DSL查询语句
  • 权限(补充)
  • 求一个无符号整数二进制形式中1的个数(三种方法)
  • DDD通用语言、多尿和尿频-《分析模式》漫谈41
  • 1. 解读DLT698.45-2017通信规约--预连接响应
  • upload-labs靶场Pass-05
  • 第五届人工智能与教育国际学术会议(ICAIE 2024)
  • (五)若使用LQR控制小车倒立摆,该如何对小车和摆杆的动力学方程线性化?哪些变量是可以进行简化的,线性化后的状态空间方程应该怎么列写
  • 瑞数后缀加密怎么处理
  • 大厂面试提问:Flash Attention 是怎么做到又快又省显存的?
  • 多线程编程
  • 多表使用use_hash hint
  • 操作系统学习笔记-1.3操作系统引导,虚拟机
  • Spark广播变量(类似小表广播)
  • 【入门篇】2.8 时钟(三)
  • 【Linux从入门到精通一】操作系统概述与Linux初识