boost propertyTree

Boost PropertyTree provides a tree structure to store key/value pairs. Tree structures means that a trunk exists with numerous branches that have numerous twigs. A file system is a good example of a tree structure. File systems have a root directory with subdirectories that themselves can have subdirectories and so on.

1. accessing data in boost::property_tree::ptree

#include <boost/property_tree/ptree.hpp>
#include <iostream>

using boost::property_tree::ptree;

int main() {
  ptree pt;
  pt.put("C:.Windows.System", "20 files");

  ptree& c = pt.get_child("C:");
  ptree& windows = c.get_child("Windows");
  ptree& system = windows.get_child("System");
  std::cout << system.get_value<std::string>() << std::endl;
  return 0;
}

put() expects two parameters because boost::property_tree::ptree is a tree structure that saves key/value pairs. The tree doesn't just consist of branches and twigs, a value must be assigned to each branch and twig.

The first parameter passed to put() is more interesting. It is a path to a directory. However, it doesn't use the backslash, which is the common path separator on Windows. It uses the dot.

To access a subbranch, you call get_child(), which returns a reference to an object of the same type get_child() was called on.

2. accessing data in basic_ptree<std::string, int>

#include <boost/property_tree/ptree.hpp>
#include <utility>
#include <iostream>

int main() {
  typedef boost::property_tree::basic_ptree<std::string, int> ptree;
  ptree pt;
  pt.put(ptree::path_type{"C:\\Windows\\System", '\\'}, 20);
  pt.put(ptree::path_type{"C:\\Windows\\Cursors", '\\'}, 50);

  ptree& windows = pt.get_child(ptree::path_type{"C:\\Windows"}, '\\');
  int files = 0;
  for (const std::pair<std::string, ptree>& p : windows) {
    files += p.second.get_value<int>();
  }
  std::cout << files << std::endl;
  return 0;
}

By default, Boost.PropertyTree uses a dot as the separator for keys. If you need to use another character, such as backslash, as the separator, you don't pass the key as a string to put(). Instand you wrap it in an object of type boost::property_tree::ptree::path_type. The constructor of this class, which depends on boost::property_tree::ptree, takes the key as its first parameter and the separator as its second parameter.

猜你喜欢

转载自www.cnblogs.com/sssblog/p/11116278.html