c++ - 在 C++ 中返回映射的函数
问题描述
有人可以给出一个在 C++ 中返回 map 的函数的实际示例。
我尝试了其他帖子的答案,但我不知道如何申请。
这是我的工作代码:
auto DataArray = jvalue.at(U("data")).as_array();
//Make an associative array or map with key value pair from extracted json data
std::map<int, std::string> staffMap;
// loop through 'data' object
for (int i = 0; i < DataArray.size(); i++)
{
try
{
auto data = DataArray[i];
auto dataObj = data.as_object();
int key;
std::string value;
// loop through each object of 'data'
for (auto iterInner = dataObj.cbegin(); iterInner != dataObj.cend(); ++iterInner)
{
auto &propertyName = iterInner->first;
auto &propertyValue = iterInner->second;
//std::wcout << "Property: " << propertyName << ", Value: " << propertyValue << std::endl;
if (propertyName == L"_id")
{
key = propertyValue.as_integer();
}
else if (propertyName == L"name")
{
value = conversions::to_utf8string(propertyValue.as_string());
}
}
staffMap.insert(std::make_pair(key, value));
}
catch (const std::exception& e)
{
std::wcout << e.what() << std::endl;
}
}
// Iterate through map and display in terminal
std::map<int, std::string>::iterator iter;
std::wcout << "The list of staffs" << std::endl;
for (iter = staffMap.begin(); iter != staffMap.end(); iter++)
std::cout << iter->first << " " << iter->second << " ,";
假设我想要一个功能:
std::map<int, std::string> staffMap;
std::map<> GetStaffMap()
{
return staffMap;
}
// Give staffMap a data here
我找不到足够的教程来制作一个在 c++ 中返回 std::map 的函数。希望有人可以在这里帮助我。谢谢你。
解决方案
我找不到足够的教程来制作一个在 c++ 中返回 std::map 的函数。希望有人可以在这里帮助我
您需要指定确切的类型,std::map<int, std::string>
:
std::map<int, std::string> GetStaffMap()
{
return staffMap;
}
如果您能够使用 C++14,请使用auto
以下选项:
auto GetStaffMap()
{
return staffMap;
}
推荐阅读
- electron - 为什么我的电子应用程序不能在任何窗口中运行?失败必须有一个合乎逻辑的解释
- sql - 如何加入一个表两次
- javascript - elasticsearch如何正确找到转义字符或保留字符?
- php - 在没有“git”命令的情况下获取 git 提交详细信息
- css - 将鼠标悬停在一个链接上时更改多个链接的颜色
- xcode - 与同级的 .sks 物理体碰撞
- laravel - 在创建函数中找不到 Laravel 页面
- r - 使用点 shapefile 将更精细的栅格数据聚合到 25 公里网格
- windows - 会话结束后是否保存 CMD 历史记录?
- python - Python脚本的定时器功能