三种容器 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()) {  
    // 元素存在  
}
`std::unordered_map` 本身是基于哈希表实现的,它不支持传统意义上像数组或有序容器那样的索引访问。`std::unordered_map` 主要通过键来访问元素,其设计目的是提供快速的键值查找,而不是基于索引的访问。 从引用内容来看,`std::unordered_map` 的初始化方式有默认构造、列表初始化和迭代器初始化等,但均未涉及建立索引的相关内容。并且像 `std::unordered_set` 这类无序容器,明确指出不提供按索引方式访问元素的功能(引用[2]),`std::unordered_map` 同样属于无序容器,因此推测它也没有内置的索引访问机制。 不过,如果有按索引访问 `std::unordered_map` 元素的需求,可以通过额外的数据结构来实现模拟索引。例如,可以创建一个存储 `std::unordered_map` 键的 `std::vector`,然后通过这个向量的索引来间接访问 `std::unordered_map` 中的元素。以下是示例代码: ```cpp #include <iostream> #include <unordered_map> #include <vector> int main() { std::unordered_map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}}; std::vector<int> keys; // 将 unordered_map 的键存储到 vector 中 for (const auto& pair : myMap) { keys.push_back(pair.first); } // 通过 vector 的索引间接访问 unordered_map 中的元素 if (keys.size() > 0) { int index = 0; int key = keys[index]; std::string value = myMap[key]; std::cout << "Element at index " << index << ": " << value << std::endl; } return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值