C++ 使用 map 容器将 string 作为 key,结构体作为 value 的示例
C++ 使用 map 容器将 string 作为 key,结构体作为 value 的示例
以下是一个使用 C++ 标准库中的 map 容器,将 key 设为 string,value 设为结构体的例子:
#include <iostream>
#include <map>
#include <string>
// 定义结构体
struct MyStruct {
int value1;
double value2;
};
int main() {
// 创建 map 容器
std::map<std::string, MyStruct> myMap;
// 插入键值对
myMap['key1'] = {10, 3.14};
myMap['key2'] = {20, 6.28};
myMap['key3'] = {30, 9.42};
// 遍历 map
for (const auto& pair : myMap) {
std::cout << "Key: " << pair.first << ", Value1: " << pair.second.value1 << ", Value2: " << pair.second.value2 << std::endl;
}
return 0;
}
这个例子中,我们创建了一个名为myMap的 map 容器,其中的 key 为 string 类型,value 为自定义的结构体MyStruct。然后我们使用插入操作将一些键值对添加到 map 中。最后,我们使用一个循环遍历 map,输出每个键值对的 key 和对应的 value 的值。
请注意,map 中的 key 是按照一定的顺序进行存储的,而不是随机的。如果你需要随机获取 map 中的键值对,可以使用其他的数据结构,例如 unordered_map。
原文地址: https://www.cveoy.top/t/topic/p8fW 著作权归作者所有。请勿转载和采集!