admin 管理员组

文章数量: 1087139


2024年3月8日发(作者:指针常量和指针变量)

在C++中,可以使用迭代器(iterator)或基于范围的for循环来遍历map。

1. 使用迭代器遍历map:

```cpp

#include

#include

using namespace std;

int main() {

map myMap;

myMap["one"] = 1;

myMap["two"] = 2;

myMap["three"] = 3;

// 使用迭代器遍历map

for (map::iterator it = (); it !=

(); it++) {

cout << "Key: " << it->first << ", Value: " << it->second <<

endl;

}

return 0;

}

```

2. 使用基于范围的for循环遍历map:

```cpp

#include

#include

using namespace std;

int main() {

map myMap;

myMap["one"] = 1;

myMap["two"] = 2;

myMap["three"] = 3;

// 使用基于范围的for循环遍历map

for (const auto &pair : myMap) {

cout << "Key: " << << ", Value: " <<

<< endl;

}

return 0;

}

```

在这两种方法中,迭代器遍历map可以更灵活地访问元素,而基于范围的for循环则更简洁。


本文标签: 指针 遍历 范围 迭代 使用