unordered_map auto
时间: 2023-11-09 07:09:42 浏览: 41
unordered_map是C++ STL中的一个容器,它是一个哈希表,可以用于存储键值对。而auto是C++11中的一个关键字,可以自动推导变量类型。在使用unordered_map时,我们可以使用auto来遍历它,这样可以省去手动指定迭代器类型的麻烦。同时,unordered_map也支持与map相同的操作,只是输出是无序的。
相关问题
unordered_map、unordered_set
unordered_map和unordered_set都是C++ STL中的关联容器,它们的底层实现都是哈希表。其中,unordered_map用于存储键值对,而unordered_set则只存储键。
使用哈希表的优点是可以在O(1)的时间复杂度内进行插入、查找和删除操作,但是在最坏情况下,哈希表的时间复杂度会退化到O(n)。
unordered_map和unordered_set的使用方法与其他STL容器类似,可以使用迭代器进行遍历,也可以使用auto关键字进行类型推导。
下面是一个使用unordered_map的例子:
```c++
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
unordered_map<string, int> umap;
umap["apple"] = 1;
umap["banana"] = 2;
umap["orange"] = 3;
for (auto it = umap.begin(); it != umap.end(); it++) {
cout << it->first << ": " << it->second << endl;
}
return 0;
}
```
输出结果为:
```
orange: 3
banana: 2
apple: 1
```
unordered_set和unordered_map的用法
unordered_set和unordered_map是C++标准库中的容器,用于存储和管理不重复的元素集合和键值对集合。
unordered_set是一个无序的集合容器,其中的元素是唯一的且无序的。它基于哈希表实现,因此插入、删除和查找操作的平均时间复杂度为常数时间O(1)。使用unordered_set可以快速判断一个元素是否存在于集合中。
unordered_map是一个无序的键值对容器,其中的键是唯一的且无序的。它也基于哈希表实现,因此插入、删除和查找操作的平均时间复杂度为常数时间O(1)。使用unordered_map可以根据键快速查找对应的值。
使用unordered_set和unordered_map时,需要包含头文件<unordered_set>和<unordered_map>。以下是它们的基本用法:
1. 创建容器:
unordered_set<int> mySet; // 创建一个空的unordered_set
unordered_map<string, int> myMap; // 创建一个空的unordered_map
2. 插入元素或键值对:
mySet.insert(10); // 插入元素10到unordered_set中
myMap["apple"] = 5; // 插入键值对("apple", 5)到unordered_map中
3. 删除元素或键值对:
mySet.erase(10); // 从unordered_set中删除元素10
myMap.erase("apple"); // 从unordered_map中删除键为"apple"的键值对
4. 查找元素或键值对:
auto it = mySet.find(10); // 在unordered_set中查找元素10,返回迭代器
if (it != mySet.end()) {
// 找到了元素
}
auto it = myMap.find("apple"); // 在unordered_map中查找键为"apple"的键值对,返回迭代器
if (it != myMap.end()) {
// 找到了键值对
int value = it->second; // 获取对应的值
}
相关推荐
![h](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)