Function sample_create_trees
Synopsis
#include <samples/quickstart.cpp>
void sample_create_trees()
Description
programatically create trees
shows how to programatically create trees
Mentioned in
- Getting Started / Quick start
Source
Lines 1639-1714 in samples/quickstart.cpp. Line 57 in samples/quickstart.cpp.
void sample_create_trees()
{
ryml::NodeRef doe;
CHECK(!doe.valid()); // it's pointing at nowhere
ryml::Tree tree;
ryml::NodeRef root = tree.rootref();
root |= ryml::MAP; // mark root as a map
doe = root["doe"];
CHECK(doe.valid()); // it's now pointing at the tree
CHECK(doe.is_seed()); // but the tree has nothing there, so this is only a seed
// set the value of the node
const char a_deer[] = "a deer, a female deer";
doe = a_deer;
// now the node really exists in the tree, and this ref is no
// longer a seed:
CHECK(!doe.is_seed());
// WATCHOUT for lifetimes:
CHECK(doe.val().str == a_deer); // it is pointing at the initial string
// If you need to avoid lifetime dependency, serialize the data:
{
std::string a_drop = "a drop of golden sun";
// this will copy the string to the tree's arena:
// (see the serialization samples below)
root["ray"] << "a drop of golden sun";
// and now you can modify the original string without changing
// the tree:
a_drop[0] = 'Z';
a_drop[1] = 'Z';
}
CHECK(root["ray"].val() == "a drop of golden sun");
// etc.
root["pi"] << ryml::fmt::real(3.141592654, 5);
root["xmas"] << ryml::fmt::boolalpha(true);
root["french-hens"] << 3;
ryml::NodeRef calling_birds = root["calling-birds"];
calling_birds |= ryml::SEQ;
calling_birds.append_child() = "huey";
calling_birds.append_child() = "dewey";
calling_birds.append_child() = "louie";
calling_birds.append_child() = "fred";
ryml::NodeRef xmas5 = root["xmas-fifth-day"];
xmas5 |= ryml::MAP;
xmas5["calling-birds"] = "four";
xmas5["french-hens"] << 3;
xmas5["golden-rings"] << 5;
xmas5["partridges"] |= ryml::MAP;
xmas5["partridges"]["count"] << 1;
xmas5["partridges"]["location"] = "a pear tree";
xmas5["turtle-doves"] = "two";
root["cars"] = "GTO";
std::cout << tree;
CHECK(ryml::emitrs<std::string>(tree) == 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
)");
}