c++20遍历map方法
时间: 2023-11-29 10:47:51 浏览: 107
C++20引入了`ranges`库,可以使用`std::views::all`和`std::views::keys`等视图函数来遍历`map`。以下是两种遍历`map`的方法:
方法一:使用`std::views::all`和`std::views::keys`视图函数遍历`map`的键和值
```c++
#include <iostream>
#include <map>
#include <ranges>
int main() {
std::map<int, std::string> myMap{{0, "aaa"}, {1, "bbb"}, {2, "ccc"}};
for (const auto& key : myMap | std::views::keys) {
std::cout << "key:" << key << " value:" << myMap[key] << std::endl;
}
return 0;
}
```
输出:
```
key:0 value:aaa
key:1 value:bbb
key:2 value:ccc
```
方法二:使用`std::ranges::for_each`和lambda表达式遍历`map`的键和值
```c++
#include <iostream>
#include <map>
#include <ranges>
int main() {
std::map<int, std::string> myMap{{0, "aaa"}, {1, "bbb"}, {2, "ccc"}};
std::ranges::for_each(myMap, [](const auto& kv) {
std::cout << "key:" << kv.first << " value:" << kv.second << std::endl;
});
return 0;
}
```
输出:
```
key:0 value:aaa
key:1 value:bbb
key:2 value:ccc
```
阅读全文