新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

如何用c++迭代器iterator遍历map,c++迭代是什么意思

发布时间:2023-10-14 08:32:34

如何用c++迭代器iterator遍历map

使用C++迭代器iterator遍历map的方法以下:

  1. 使用begin()函数获得map的起始迭代器。
  2. 使用end()函数获得map的结束迭代器。
  3. 使用循环结构(如for循环、while循环)和迭代器逐一遍历map中的元素,直到迭代器到达结束位置为止。
  4. 在循环中使用迭代器的first和second成员访问map中的键和值。

以下是一个示例代码:

#include 
#include 
int main() {
std::map myMap;
myMap[1] = "One";
myMap[2] = "Two";
myMap[3] = "Three";
// 使用迭代器遍历map
std::map::iterator it;
for (it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << "Key: " << it->first << " Value: " << it->second << std::endl;
}
return 0;
}

运行结果:

Key: 1 Value: One
Key: 2 Value: Two
Key: 3 Value: Three