unordered_map中at函数怎么对形参使用
时间: 2023-10-13 14:16:19 浏览: 45
`std::unordered_map` 的 `at` 函数可以用于访问指定键所对应的值。它的语法如下:
```c++
T& at( const Key& key );
const T& at( const Key& key ) const;
```
其中,`key` 是指要查找的键。如果键存在,则返回对应的值的引用,否则会抛出 `std::out_of_range` 异常。
例如,若要访问 `std::unordered_map<std::string, int> myMap` 中键为 `"hello"` 的值,可以使用以下代码:
```c++
int value = myMap.at("hello");
```
注意,如果你对一个不存在的键使用 `at` 函数,则会抛出 `std::out_of_range` 异常。因此,在使用 `at` 函数之前,应该先使用 `count` 函数检查该键是否存在。
相关问题
怎么对形参使用unordered_map中at函数
unordered_map中的at函数可以用来获取一个键对应的值。使用方法如下:
```c++
std::unordered_map<std::string, int> umap = {{"apple", 1}, {"banana", 2}, {"orange", 3}};
int value = umap.at("apple"); // 获取键"apple"对应的值,即1
```
如果键不存在,at函数会抛出一个std::out_of_range异常。因此,在使用at函数之前,最好先使用count函数判断键是否存在,如下所示:
```c++
if (umap.count("apple")) {
int value = umap.at("apple");
// ...
}
else {
// 键不存在
}
```
注意,at函数只能对非const的unordered_map使用,如果unordered_map是const的,则需要使用find函数来获取键对应的值。
unordered_map中的函数
unordered_map是C++标准库中的一个容器,它提供了一种键值对的映射关系。下面是一些unordered_map中常用的函数:
1. insert(key, value):向unordered_map中插入一个键值对。
2. erase(key):从unordered_map中删除指定键的元素。
3. find(key):在unordered_map中查找指定键的元素,返回一个迭代器。
4. count(key):返回unordered_map中指定键的元素个数,由于unordered_map中键是唯一的,所以返回值只能是0或1。
5. size():返回unordered_map中元素的个数。
6. empty():判断unordered_map是否为空,如果为空则返回true,否则返回false。
7. clear():清空unordered_map中的所有元素。
8. begin()和end():返回指向unordered_map中第一个元素和最后一个元素之后位置的迭代器。
9. operator[]:通过键访问unordered_map中的值,如果键不存在,则会插入一个新的键值对。
10. at(key):通过键访问unordered_map中的值,如果键不存在,则会抛出异常。
以上是unordered_map中一些常用的函数,可以根据具体需求选择使用。如果还有其他问题,请继续提问。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)