请求C++返回map的函数实例及现有JSON代码适配方法
C++ 返回map的函数完整示例(适配JSON数据提取场景)
没问题!结合你给出的JSON提取代码,我写一个完整的可运行示例,帮你实现从JSON数组生成并返回std::map<int, std::string>的函数。从你代码里的jvalue、U("data")来看,应该用的是Windows Runtime的JSON API,咱直接上代码:
完整函数实现
#include <map> #include <string> #include <iostream> #include <winrt/Windows.Data.Json.h> // 从JSON数据中提取staff信息,返回int(员工ID)到string(员工名称/目标字段)的map std::map<int, std::string> parseStaffData(const winrt::Windows::Data::Json::JsonValue& jvalue) { std::map<int, std::string> staffMap; try { // 提取JSON中的"data"数组 auto DataArray = jvalue.at(winrt::hstring(U("data"))).as_array(); // 遍历数组中的每个对象(用范围for更简洁,也可以保留你原来的索引循环) for (const auto& data : DataArray) { auto dataObj = data.as_object(); // 补全你未完成的部分:提取key和value(这里假设JSON字段是"id"和"name",按需修改) int staffId = static_cast<int>(dataObj.at(winrt::hstring(U("id"))).as_number()); std::string staffInfo = winrt::to_string(dataObj.at(winrt::hstring(U("name"))).as_string()); // 插入map,emplace比insert更高效 staffMap.emplace(staffId, staffInfo); } } catch (const winrt::hresult_error& ex) { // 处理JSON解析异常:比如字段缺失、类型不匹配 std::cerr << "JSON解析出错: " << winrt::to_string(ex.message()) << std::endl; // 这里可以选择返回空map,或者重新抛出异常,根据你的业务需求调整 throw; } return staffMap; }
调用示例
int main() { // 假设你已经获取了JSON数据(比如从文件/网络加载后的jvalue) winrt::Windows::Data::Json::JsonValue jvalue = /* 你的JSON数据源 */; try { // 调用函数拿到返回的map auto staffMap = parseStaffData(jvalue); // 遍历输出验证结果 for (const auto& [id, info] : staffMap) { std::cout << "员工ID: " << id << ", 信息: " << info << std::endl; } } catch (const std::exception& ex) { std::cerr << "处理失败: " << ex.what() << std::endl; } return 0; }
关键说明
- 我补全了你代码里未完成的字段提取逻辑,你可以根据实际的JSON字段名(比如把
"name"改成你需要的字段)直接修改。 - C++中返回
std::map非常直接,编译器会自动优化返回值的传递(通常是移动语义,不会有额外性能负担)。 - 保留了你原来的
try-catch异常处理,针对WinRT的hresult_error做了捕获,你可以根据自己的错误处理策略调整(比如返回空map、记录日志等)。
内容的提问来源于stack exchange,提问作者noyruto88
相关产品推荐
相关产品推荐

