#include <iostream>
#include <map>
int main() {
// 创建一个map,键为整数,值为字符串
std::map<int, std::string> myMap;
// 向map中插入一些元素
myMap[1] = "one";
myMap[2] = "two";
myMap[3] = "three";
// 方法1: 使用迭代器遍历map
std::cout << "方法1: 使用迭代器遍历map" << std::endl;
for (std::map<int, std::string>::iterator it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
// 方法2: 使用范围for循环(C++11及以上版本)
std::cout << "\n方法2: 使用范围for循环遍历map" << std::endl;
for (const auto& pair : myMap) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
// 方法3: 使用基于范围的for循环和结构化绑定(C++17及以上版本)
std::cout << "\n方法3: 使用基于范围的for循环和结构化绑定遍历map" << std::endl;
for (const auto& [key, value] : myMap) {
std::cout << "Key: " << key << ", Value: " << value << std::endl;
}
return 0;
}
std::map<int, std::string>类型的map,并向其中插入了一些键值对。std::map::iterator来遍历map中的每个元素,访问键和值。上一篇:c++ set用法
下一篇:c++ sin
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站