下面是一个使用迭代器遍历std::map<int, int>的示例代码:
#include <iostream>
#include <map>
int main() {
// 创建一个 map,键和值都是 int 类型 std::map<int, int> myMap; // 插入一些键值对 myMap[1] = 100;
myMap[2] = 200;
myMap[3] = 300;
// 使用迭代器遍历 map
for (std::map<int, int>::iterator it = myMap.begin(); it != myMap.end(); ++it) {
// it->first 是键,it->second 是值 std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
// 也可以使用 C++11 的范围 for 循环(更简洁)
std::cout << "Using range-based for loop:" << std::endl;
for (const auto& pair : myMap) { std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
return 0;
}
vector:
#include <iostream>
#include <vector>
int main() {
// 创建一个 vector,存储 int 类型的元素
std::vector<int> myVector = {10, 20, 30, 40, 50};
// 使用迭代器遍历 vector
for (std::vector<int>::iterator it = myVector.begin(); it != myVector.end(); ++it) {
// 使用 *it 访问当前元素
std::cout << "Element: " << *it << std::endl;
}
// 也可以使用 C++11 的范围 for 循环(更简洁)
std::cout << "Using range-based for loop:" << std::endl;
for (const int& element : myVector) {
std::cout << "Element: " << element << std::endl;
}
return 0;
}