Function sample_iterate_trees
Synopsis
#include <samples/quickstart.cpp>
void sample_iterate_trees()
Description
visit individual nodes and iterate through trees
shows how to programatically iterate through trees
Mentioned in
- Getting Started / Quick start
Source
Lines 1577-1633 in samples/quickstart.cpp. Line 56 in samples/quickstart.cpp.
void sample_iterate_trees()
{
ryml::Tree tree = ryml::parse(R"(doe: "a deer, a female deer"
ray: "a drop of golden sun"
pi: 3.14159
xmas: true
french-hens: 3
calling-birds:
- huey
- dewey
- louie
- fred
xmas-fifth-day:
calling-birds: four
french-hens: 3
golden-rings: 5
partridges:
count: 1
location: a pear tree
turtle-doves: two
cars: GTO
)");
ryml::NodeRef root = tree.rootref();
// iterate children
{
std::vector<ryml::csubstr> keys, vals; // to store all the root-level keys, vals
for(ryml::NodeRef n : root.children())
{
keys.emplace_back(n.key());
vals.emplace_back(n.has_val() ? n.val() : ryml::csubstr{});
}
CHECK(keys[0] == "doe");
CHECK(vals[0] == "a deer, a female deer");
CHECK(keys[1] == "ray");
CHECK(vals[1] == "a drop of golden sun");
CHECK(keys[2] == "pi");
CHECK(vals[2] == "3.14159");
CHECK(keys[3] == "xmas");
CHECK(vals[3] == "true");
CHECK(root[5].has_key());
CHECK(root[5].is_seq());
CHECK(root[5].key() == "calling-birds");
CHECK(!root[5].has_val()); // it is a map, so not a val
//CHECK(root[5].val() == ""); // ERROR! node does not have a val.
CHECK(keys[5] == "calling-birds");
CHECK(vals[5] == "");
}
// iterate siblings
{
size_t count = 0;
ryml::csubstr calling_birds[] = {"huey", "dewey", "louie", "fred"};
for(ryml::NodeRef n : root["calling-birds"][2].siblings())
CHECK(n.val() == calling_birds[count++]);
}
}