Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++ 读取json map

作者:任光阴风干ゝ影象   发布日期:2025-08-04   浏览:73

#include <iostream>
#include <fstream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
    // 读取 JSON 文件
    std::ifstream file("example.json");
    if (!file.is_open()) {
        std::cerr << "无法打开文件" << std::endl;
        return 1;
    }

    // 解析 JSON 文件内容到 json 对象
    json j;
    file >> j;
    file.close();

    // 将 JSON 对象转换为 C++ map
    std::map<std::string, int> my_map = j.get<std::map<std::string, int>>();

    // 打印 map 内容
    for (const auto& [key, value] : my_map) {
        std::cout << key << ": " << value << std::endl;
    }

    return 0;
}

解释说明:

  1. 引入头文件#include <nlohmann/json.hpp> 引入了 nlohmann/json 库,用于处理 JSON 数据。
  2. 定义别名using json = nlohmann::json;nlohmann::json 类型定义了一个简短的别名 json
  3. 读取文件:使用 std::ifstream 打开并读取 JSON 文件。
  4. 解析 JSON:将文件内容解析为 json 对象。
  5. 转换为 map:使用 get<std::map<std::string, int>>() 方法将 JSON 对象转换为 C++ 的 std::map
  6. 遍历和打印:使用范围循环遍历 std::map 并打印键值对。

确保你已经安装了 nlohmann/json 库。可以使用以下命令通过包管理器安装:

pip install nlohmann_json

或者在 CMake 中添加依赖项。

上一篇:postcss.config.js

下一篇:js 数组 reduce

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象转数组

js 深拷贝数组

js 点击空白区域触发事件

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站