#include <iostream>
#include <map>
int main() {
// 创建一个map,键为字符串,值为整数
std::map<std::string, int> myMap = {{"apple", 1}, {"banana", 2}, {"cherry", 3}};
// 方法1: 使用基于范围的for循环遍历map
std::cout << "Method 1: Range-based for loop" << std::endl;
for (const auto& pair : myMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
// 方法2: 使用迭代器遍历map
std::cout << "\nMethod 2: Iterator" << std::endl;
for (std::map<std::string, int>::iterator it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
// 方法3: 使用C++11的auto关键字和迭代器遍历map
std::cout << "\nMethod 3: C++11 auto and iterator" << std::endl;
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
// 方法4: 使用C++11的auto关键字和基于范围的for循环遍历map
std::cout << "\nMethod 4: C++11 auto and range-based for loop" << std::endl;
for (const auto& [key, value] : myMap) {
std::cout << key << ": " << value << std::endl;
}
return 0;
}
std::map,其中键是 std::string 类型,值是 int 类型。map 中的每个键值对。begin() 到 end() 遍历 map,这种方式在 C++98/03 中常用。auto 关键字和迭代器:简化了代码,减少了类型声明。auto 和基于范围的for循环,进一步简化了代码,直接解构出键和值。每种方法都能有效地遍历 map,选择哪种方式取决于你的编码风格和 C++ 标准版本。
上一篇:c++获取数组长度
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站