简体   繁体   中英

How to parse a file with yaml-cpp

I have a yaml file that looks like this:

construction_cone_1:
  model: construction_cone
  model_type: sdf
  position: [ 1.2, 3.4, 0.0 ]
  orientation: [ 0.0, 0.0, 0 ]
  
construction_cone_2:
  model: construction_cone
  model_type: sdf
  position: [ 3.0, 7.0, 0.0 ]
  orientation: [ 0.0, 0.0, 0 ]
 
...

I'm following this tutorial to parse it in my c++ application.

What I understood so far is that, as it is structured, the file is loaded as a map into a YAML::Node . So, I guess, a good way to read it is:

YAML::Node map = YAML::LoadFile(file_path);
  for(YAML::const_iterator it=map.begin(); it!=map.end(); ++it){
    const std::string &key=it->first.as<std::string>();

This gives me "construction_cone_1" for the first entry and so on. By following this logic I'm not able to figure out how to read the remainder. In particular, for each entry of the map, I'm interested in reading the object position.

I guess I underestimated the power of the library. It turns out that doing so solves the problem:

  YAML::Node map = YAML::LoadFile(filename);
  for(YAML::const_iterator it=map.begin(); it!=map.end(); ++it){
    const std::string &key=it->first.as<std::string>();

    Eigen::Vector2f pos;
    YAML::Node attributes = it->second;
    YAML::Node position = attributes["position"];
    for(int i=0; i<2; ++i){
      pos(i) = position[i].as<float>();
    }

    ...
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM