#include <iostream>
#include <map>
#include <string>
int main() {
// 创建一个 map,键为 string 类型,值为 int 类型
std::map<std::string, int> myMap;
// 向 map 中插入一些数据
myMap["apple"] = 3;
myMap["banana"] = 5;
myMap["orange"] = 2;
// 方法1:使用迭代器遍历 map
std::cout << "Method 1: Using iterator" << std::endl;
for (std::map<std::string, int>::iterator it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
// 方法2:使用基于范围的 for 循环(C++11 及以上版本)
std::cout << "\nMethod 2: Using range-based for loop" << std::endl;
for (const auto& pair : myMap) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
// 方法3:使用 C++17 的结构化绑定(C++17 及以上版本)
std::cout << "\nMethod 3: Using structured bindings (C++17)" << std::endl;
for (const auto& [key, value] : myMap) {
std::cout << "Key: " << key << ", Value: " << value << std::endl;
}
return 0;
}
创建和初始化 map:
std::map<std::string, int> 创建了一个映射,其中键是字符串类型,值是整数类型。myMap["key"] = value; 插入了一些键值对。方法1:使用迭代器遍历 map:
std::map::iterator 来遍历 map。通过 begin() 和 end() 获取迭代器范围,并在循环中访问每个元素的键和值。方法2:使用基于范围的 for 循环:
auto 关键字让编译器自动推导出迭代变量的类型。pair.first 是键,pair.second 是值。方法3:使用 C++17 的结构化绑定:
pair,直接将键和值绑定到两个变量上。for (const auto& [key, value] : myMap) 直接将键和值分别绑定到 key 和 value 上。上一篇:c++ mfc
下一篇:c++set用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站