unordered_map的异常处理机制与错误调试技巧
发布时间: 2024-04-11 12:49:29 阅读量: 53 订阅数: 80 ![](https://csdnimg.cn/release/wenkucmsfe/public/img/col_vip.0fdee7e1.png)
![](https://csdnimg.cn/release/wenkucmsfe/public/img/col_vip.0fdee7e1.png)
![PPT](https://csdnimg.cn/release/download/static_files/pc/images/minetype/PPT.png)
异常处理机制
# 1. unordered_map 容器的概述和基本操作
- **unordered_map 容器简介**
unordered_map 是 C++ STL 中的关联容器之一,采用哈希表实现,能够快速通过键值对查找元素。与 map 相比,unordered_map 不会对元素进行排序,插入和访问操作的时间复杂度为 O(1)。
- **unordered_map 容器的声明和初始化**
- 创建空的 unordered_map 对象:
```cpp
unordered_map<int, string> myMap;
```
- 初始化带有初始元素的 unordered_map 对象:
```cpp
unordered_map<int, string> myMap = {{1, "apple"}, {2, "banana"}};
```
未完,待续...
# 2. unordered_map 容器的插入和访问操作
#### 向 unordered_map 容器插入元素
##### 使用 insert() 方法插入元素
在 unordered_map 容器中,可以使用 insert() 方法向容器中插入新的键值对。insert() 方法接受一个 std::pair 类型的参数,其中第一个元素为键,第二个元素为值。下面是一个示例代码:
```cpp
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> umap;
// 使用 insert() 方法插入元素
umap.insert(std::make_pair(1, "apple"));
umap.insert(std::make_pair(2, "banana"));
umap.insert(std::make_pair(3, "cherry"));
return 0;
}
```
##### 使用 emplace() 方法插入元素
除了 insert() 方法外,还可以使用 emplace() 方法来插入元素。emplace() 方法接受参数包作为参数,直接构造键值对并插入容器中。示例如下:
```cpp
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> umap;
// 使用 emplace() 方法插入元素
umap.emplace(1, "apple");
umap.emplace(2, "banana");
umap.emplace(3, "cherry");
return 0;
}
```
#### 通过键值访问 unordered_map 中的元素
##### 使用 [] 运算符访问元素
通过 [] 运算符,可以根据键值直接访问 unordered_map 容器中的元素。如果键值存在,则返回对应的值;如果键值不存在,则会插入一个新的键值对。示例如下:
```cpp
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> umap = {{1, "apple"}, {2, "banana"}, {3, "cherry"}};
// 使用 [] 运算符访问元素
std::cout << umap[2] << std::endl; // 输出 "banana"
return 0;
}
```
##### 使用 at() 方法访问元素
另一种访问元素的方式是使用 at() 方法,通过传入键值来获取对应的值。如果键值不存在,则会抛出异常。示例如下:
```cpp
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> umap = {{1, "apple"}, {2, "banana"}, {3, "cherry"}};
// 使用 at() 方法访问元素
s
```
0
0
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)