Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 975
Federico Nardi Avatar asked Oct 21 '25 04:10

Federico Nardi


1 Answers

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>();
    }

    ...
  }
like image 163
Federico Nardi Avatar answered Oct 23 '25 20:10

Federico Nardi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!