You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用yaml-cpp按id值高效获取YAML文件中对应节点的详细信息

yaml-cpp高效查询指定id条目的方案

针对你给出的传感器列表类YAML结构,有两种优化方案,分别对应单次查询和多次查询的场景:

方案1:单次查询(仅查1次指定id)

直接遍历sensors数组,匹配到目标id后立即终止遍历,无需走完全量数组。

示例代码

#include <iostream>
#include <yaml-cpp/yaml.h>

int main() {
    // 加载YAML文件,仅执行一次
    YAML::Node config = YAML::LoadFile("config.yaml");
    const YAML::Node& sensors = config["sensors"];

    const int target_id = 5;
    for (const auto& sensor : sensors) {
        if (sensor["id"].as<int>() == target_id) {
            // 匹配到目标后直接输出并退出循环
            std::cout << "hardwareId: " << sensor["hardwareId"].as<std::string>() << "\n";
            std::cout << "type: " << sensor["type"].as<std::string>() << "\n";
            break;
        }
    }
    return 0;
}

效率说明

平均时间复杂度O(n/2),如果id有序可以改用二分查找优化到O(logn)。

方案2:多次查询(需要频繁查不同id)

首次加载文件时一次性构建id到传感器信息的哈希映射,后续所有查询都可以直接走哈希表查找,效率最高。

示例代码

#include <iostream>
#include <unordered_map>
#include <yaml-cpp/yaml.h>

// 自定义结构体存储传感器信息,也可以直接存YAML::Node节省转换开销
struct Sensor {
    int id;
    std::string hardwareId;
    std::string type;
};

int main() {
    YAML::Node config = YAML::LoadFile("config.yaml");
    const YAML::Node& sensors = config["sensors"];

    // 仅首次加载时构建一次索引
    std::unordered_map<int, Sensor> sensor_map;
    for (const auto& node : sensors) {
        Sensor s;
        s.id = node["id"].as<int>();
        s.hardwareId = node["hardwareId"].as<std::string>();
        s.type = node["type"].as<std::string>();
        sensor_map.emplace(s.id, std::move(s));
    }

    // 后续任意次数查询都是O(1)时间复杂度
    const int target_id = 5;
    // 低于C++20标准可替换为 sensor_map.find(target_id) != sensor_map.end()
    if (sensor_map.contains(target_id)) {
        const auto& s = sensor_map.at(target_id);
        std::cout << "hardwareId: " << s.hardwareId << "\n";
        std::cout << "type: " << s.type << "\n";
    }
    return 0;
}

效率说明

索引构建时间O(n),后续查询时间复杂度O(1),适合传感器条目多、查询频繁的场景。

内容的提问来源于stack exchange,提问作者neo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 08:06:01