yaml-cpp read sequence in item(yaml-cpp 读取项目中的序列)
问题描述
如何使用 yaml-cpp 读取此 YAML 文件:
How can I read this YAML file with yaml-cpp:
sensors:
- id: 5
hardwareId: 28-000005a32133
type: 1
- id: 6
hardwareId: 28-000005a32132
type: 4
我不明白如何获得 sensors 项目,以使用它.
I can't understand how can I get sensors item, to use it.
据我了解,sensors 是一个 YAML::Node.我怎样才能得到它?
As I understand sensors is a YAML::Node. How can I get it?
更新 1:
YAML::Node config = YAML::LoadFile(config_path);
const YAML::Node& node_test1 = confg["sensors"];
for (std::size_t i = 0; i < node_test1.size(); i++) {
const YAML::Node& node_test2 = node_test1[i];
std::cout << "Id: " << node_test2["id"].as<std::string>() << std::endl;
std::cout << "hardwareId: " << node_test2["hardwareId"].as<std::string>() << std::endl << std::endl;
}
此代码有效,但它是使用有关旧 api 的教程编写的.我认为这段代码可以用迭代器重写,但我现在不知道如何.
This code works, but it was writed using tutorial about old api. I think this code could be rewrited with iterators, but I don't now how.
推荐答案
看起来你的代码可以工作,但是如果你想用迭代器重写它,你可以:
It looks like your code works, but if you want to rewrite it with iterators, you can:
YAML::Node config = YAML::LoadFile(config_path);
const YAML::Node& sensors = config["sensors"];
for (YAML::iterator it = sensors.begin(); it != sensors.end(); ++it) {
const YAML::Node& sensor = *it;
std::cout << "Id: " << sensor["id"].as<std::string>() << "
";
std::cout << "hardwareId: " << sensor["hardwareId"].as<std::string>() << "
";
}
这篇关于yaml-cpp 读取项目中的序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:yaml-cpp 读取项目中的序列
基础教程推荐
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
