c++ unordered_map的遍历
时间: 2023-11-07 14:05:54 浏览: 125
使用 `unordered_map` 可以通过迭代器进行遍历,可以使用 `auto` 进行类型推导,示例代码如下:
```c++
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> umap = {{"apple", 1}, {"banana", 2}, {"cherry", 3}};
// 使用 auto 进行类型推导,pair 的 first 是 key,second 是 value
for (const auto& pair : umap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
```
输出结果为:
```
apple: 1
banana: 2
cherry: 3
```
相关问题
c++unordered_map反向遍历
要反向遍历一个 `unordered_map`,你可以使用逆向迭代器(`reverse_iterator`)来实现。以下是一个示例代码:
```c++
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}};
for (auto itr = myMap.rbegin(); itr != myMap.rend(); ++itr) {
std::cout << "Key: " << itr->first << ", Value: " << itr->second << std::endl;
}
return 0;
}
```
这个代码将输出:
```
Key: 3, Value: three
Key: 2, Value: two
Key: 1, Value: one
```
在 `for` 循环中,我们使用 `rbegin()` 和 `rend()` 来获取逆向迭代器的起始和结束位置,然后通过 `++itr` 来向前移动迭代器。通过 `itr->first` 和 `itr->second` 可以访问键和值。
希望这个示例对你有帮助!如果你还有其他问题,请随时提问。
unordered_map怎么遍历
以下是三种unordered_map遍历的方法:
1. 值传递遍历:
```c++
unordered_map<int, int> map = { {1, 2}, {3, 4} };
for (pair<int, int> kv : map) {
cout << kv.first << kv.second << endl;
}
```
2. 使用auto:
```c++
unordered_map<int, int> map = { {1, 2}, {3, 4} };
for (auto& kv : map) {
cout << kv.first << kv.second << endl;
}
```
3. 使用迭代器遍历:
```c++
unordered_map<int, int> map = { {1, 2}, {3, 4} };
for (unordered_map<int, int>::iterator it = map.begin(); it != map.end(); it++) {
cout << it->first << it->second << endl;
}
```
阅读全文
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)