#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, int> _map;
_map[0] = 1;
_map[1] = 2;
_map[10] = 10;
map<int, int>::iterator iter;
iter = _map.begin();
while(iter != _map.end()) {
cout << iter->first << " : " << iter->second << endl;
iter++;
}
// 也可以使用for循环遍历
/*
for(iter = _map.begin(); iter != _map.end(); iter++) { //如果使用for循环遍历map,不能写成 ‘<’ 的形式
cout << iter->first << " : " << iter->second << endl;
}
*/
return 0;
}程序的运行结果为:
本文介绍了一个使用C++标准模板库(STL)中map容器的基本示例,展示了如何初始化map并利用迭代器进行遍历输出。通过具体的代码实现了map的增删改查操作,并比较了while循环和for循环两种遍历方式。
6万+

被折叠的 条评论
为什么被折叠?



