怎么使用std::foreach遍历unorderedmap
时间: 2023-05-26 10:05:41 浏览: 258
可以使用C++11的范围for循环或者std::for_each来遍历unordered_map。下面是两种方法的示例:
1. C++11的范围for循环
```cpp
#include <iostream>
#include <unordered_map>
int main()
{
std::unordered_map<std::string, int> mymap = {{"apple", 1}, {"banana", 2}, {"cherry", 3}};
for (auto& pair : mymap) {
std::cout << pair.first << ": " << pair.second << '\n';
}
return 0;
}
```
输出:
```cpp
apple: 1
banana: 2
cherry: 3
```
2. std::for_each
```cpp
#include <iostream>
#include <unordered_map>
#include <algorithm>
int main()
{
std::unordered_map<std::string, int> mymap = {{"apple", 1}, {"banana", 2}, {"cherry", 3}};
std::for_each(mymap.begin(), mymap.end(), [](const auto& pair) {
std::cout << pair.first << ": " << pair.second << '\n';
});
return 0;
}
```
输出:
```cpp
apple: 1
banana: 2
cherry: 3
```
阅读全文