Property tree resembles (almost is) a standard container with value type of
It has the usual member functions, such as
etc. These can of course be used to populate and access the tree. For example
the following code adds key
with data (almost) equal to mathematical pi value:
To find the value of
might do the following:
const_iteratorit = pt.
find("pi"); double pi = boost::lexical_cast<double>(it->second._ptree_data__());
This looks quite cumbersome, and would be even more so if
value was not stored so near the top of the tree, and we cared just a little
bit more about errors. Fortunately, there is another, correct way of doing
There are three versions of get: get, get (default-value version), and get_optional, which differ by failure handling strategy. All versions take path specifier, which determines in which key to search for a value. It can be a single key, or a path to key, where path elements are separated with a special character (a '.' if not specified differently). For example debug.logging.errorlevel might be a valid path with dot as a separator.
ptree_bad_pathexception. If value could not be translated, it will be
ptree_bad_data. Both of them derive from
ptree_errorto make common handling possible.
This version uses boost::optional class to handle extraction failure. On successful extraction, it will return boost::optional initialized with extracted value. Otherwise, it will return uninitialized boost::optional.
ptreept; /* ... */ boost::optional<float> v = pt.
To retrieve value from this tree (not some subkey), use
(default-value version), and
They have identical semantics to
functions, except they don't take the
parameter. Don't call
with and empty
to do this as it will try to extract contents of subkey with empty name.
To use separator character other than default '
versions has another form, which takes an additional parameter in front of
path. This parameter of type
the separating character. This is a lifesaving device for those who may have
dots in their keys:
pt.get<float>('/', "p.a.t.h/t.o/v.a.l.u.e"); pt.get('/', "p.a.t.h/t.o/v.a.l.u.e", 0, NULL); pt.get_optional<std::string>('/', "p.a.t.h/t.o/v.a.l.u.e");
there is a
function. Contrary to
it has only one variant. The reason is, there is no need to handle put failures
so often (normally,
will only fail if conversion of the supplied value to
fails or the system runs out of memory. In the former case,
Sample usage of
might appear as:
will insert a new value at specified path, so that a call to
specifying the same path will retrieve it. Further,
will insert any missing path elements during path traversal. For example, calling
on an empty tree will insert three new children:
key1.key2.key3. The last one will receive a string
"3.14" as data, while
the two former ones will have empty data strings.
always inserts new keys at the back of the existing sequences.