普通for遍历map集合详细步骤
时间: 2023-06-15 13:05:23 浏览: 67
遍历map集合有两种方法:使用迭代器(iterator)或者使用for循环。这里介绍使用for循环的方法:
1. 获取map的迭代器(iterator),将其指向map的第一个元素:
```cpp
map<int, string> myMap;
// 填充map
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
// 迭代器it指向了当前元素
}
```
2. 使用for循环遍历map,通过迭代器访问每个元素:
```cpp
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
// 访问key和value
int key = it->first;
string value = it->second;
// 打印
cout << "key: " << key << ", value: " << value << endl;
}
```
3. 如果你使用的是C++11或更高版本,可以使用auto关键字来避免手动指定迭代器类型:
```cpp
for (auto& [key, value] : myMap) {
// 打印
cout << "key: " << key << ", value: " << value << endl;
}
```
这样就可以遍历map集合了。注意,在遍历map集合时,元素的顺序是按key的升序排列的。如果需要按其它顺序遍历,需要使用自定义的比较器(Comparator)。