怎么用c++迭代器iterator遍历map

   2025-02-18 2190
核心提示:使用C++迭代器iterator遍历map的方法如下:使用begin()函数获取map的起始迭代器。使用end()函数获取map的结束迭代器。使用循环结

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

使用begin()函数获取map的起始迭代器。

使用end()函数获取map的结束迭代器。

使用循环结构(如for循环、while循环)和迭代器逐个遍历map中的元素,直到迭代器达到结束位置为止。

在循环中使用迭代器的first和second成员访问map中的键和值。

以下是一个示例代码:

#include <iostream>#include <map>int main() {std::map<int, std::string> myMap;myMap[1] = "One";myMap[2] = "Two";myMap[3] = "Three";// 使用迭代器遍历mapstd::map<int, std::string>::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: OneKey: 2 Value: TwoKey: 3 Value: Three

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言