I am getting started with yaml-cpp, and I am having troubles decoding one part of my file. The file that I want to decode looks like this:
leds:
- [251, 252,253]
- [254, 250,220]
- [230, 231,230]
this is how I have been trying to implement but so far is not working.
namespace YAML {
template<>
struct convert<Led_Yaml>
{
static Node encode(const Led_Yaml& led_data)
{
Node node;
node.push_back(led_data.r);
node.push_back(led_data.g);
node.push_back(led_data.b);
return node;
}
static bool decode(const Node& node, Led_Yaml& led_data)
{
led_data.r = node[0].as<int>();
led_data.g = node[1].as<int>();
led_data.b = node[2].as<int>();
return true;
}
};
}
void YAML_LedParser(std::string filename)
{
try
{
YAML::Node led_set = YAML::LoadFile(filename);
for(std::size_t i = 0; i< led_set.size();++i)
{
if(led_set["leds"])
{
std::cout<<"iteration\n";
led_collec = it->second.as<Led_Collection_Yaml>();
}
if(led_set.IsSequence())
{
//dummy = led_set[i].as<<Led_Yaml>();
led_collection.push_back(led_set[i].as<Led_Yaml>());
//std::cout<<"Got a Sequence!"<<"\n";
std::cout<<"r: "<<led_collection[i].r<<"\n";
}
}
//led_collec = led_set["leds"].as<Led_Collection>();
}
catch(YAML::ParserException& e)
{
std::cout << "Failed to load file: "<<e.what()<<"\n";
return;
}
}
The problem that I am facing is that I don't know how to parse a list of sequences
The simplest thing to do, if you know that that's the structure of your YAML, is:
std::vector<Led_Yaml> leds = led_set["leds"].as<std::vector<Led_Yaml>>();
If you actually want to iterate through your sequence manually:
for (auto element : led_set["leds"]) {
Led_Yaml led = element.as<Led_Yaml>();
// do something with led
}