帮忙写一个 返回值是std::unordered_map<std::string, std::string>的函数
时间: 2024-08-15 20:07:22 浏览: 69
要编写一个返回 std::unordered_map<std::string, std::string>
类型的函数,我们需要首先导入必要的头文件,然后创建并填充一个这样的 map。下面是一个示例代码:
#include <iostream>
#include <map>
#include <string>
// 定义一个返回 std::unordered_map<std::string, std::string> 的函数
std::unordered_map<std::string, std::string> createStringMap() {
// 初始化一个 unordered_map 并添加一些键值对作为示例数据
std::unordered_map<std::string, std::string> sampleMap = {{"key1", "value1"},
{"key2", "value2"},
{"key3", "value3"}};
return sampleMap; // 返回初始化后的 unordered_map
}
int main() {
// 调用函数并打印结果
auto result = createStringMap();
for (const auto &pair : result) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
return 0;
}
解释
头文件:
#include <iostream>, #include <map>, #include <string>
- 导入了用于处理输入输出、映射容器以及字符串的基本库。函数定义:
- 函数名为
createStringMap()
,它没有任何参数,并且返回一个std::unordered_map<std::string, std::string>
类型的对象。
- 函数名为
初始化 map:在函数内部,我们声明了一个名为
sampleMap
的std::unordered_map<std::string, std::string>
对象,并通过插入{key, value}
对的方式为其填充了一些初始数据。函数返回:最后,将初始化好的
sampleMap
直接返回给调用者。主函数 (
main()
): 这里调用了createStringMap()
函数,并遍历返回的结果 map 打印出每个键值对。
相关推荐


















