C++遍历map的key和value
时间: 2023-11-07 19:10:01 浏览: 168
可以使用迭代器来遍历map的key和value,示例代码如下:
```cpp
#include <iostream>
#include <map>
int main()
{
std::map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}};
// 遍历key
std::cout << "Keys: ";
for (auto const& pair : myMap)
{
std::cout << pair.first << " ";
}
std::cout << std::endl;
// 遍历value
std::cout << "Values: ";
for (auto const& pair : myMap)
{
std::cout << pair.second << " ";
}
std::cout << std::endl;
// 遍历key和value
std::cout << "Keys and values: ";
for (auto const& pair : myMap)
{
std::cout << "{" << pair.first << ", " << pair.second << "} ";
}
std::cout << std::endl;
return 0;
}
```
输出结果为:
```
Keys: 1 2 3
Values: one two three
Keys and values: {1, one} {2, two} {3, three}
```
阅读全文