#include <iostream>
#include <map>
int main() {
// 创建一个map,键为int类型,值为string类型
std::map<int, std::string> myMap;
// 向map中插入一些数据
myMap[1] = "Apple";
myMap[2] = "Banana";
myMap[3] = "Cherry";
// 方法1:使用基于范围的for循环遍历map
for (const auto& pair : myMap) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
// 方法2:使用迭代器遍历map
for (std::map<int, std::string>::iterator it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
// 方法3:使用C++11的auto关键字和迭代器遍历map
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
return 0;
}
创建和初始化map:
std::map<int, std::string> 创建了一个名为 myMap 的映射,其中键为整数类型,值为字符串类型。myMap 中插入了一些键值对。遍历map的方法:
for 循环(C++11 及以上版本支持)。这种方式简洁且易读,适合大多数情况。auto 关键字简化迭代器的声明。这种方式既保持了代码的简洁性,又避免了显式指定迭代器类型。每种方法都会输出 myMap 中的所有键值对。
上一篇:c++ memcpy
下一篇:c++ 单例模式
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站