码迷,mamicode.com
首页 > 其他好文 > 详细

boost propertyTree

时间:2019-07-01 19:55:26      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:out   put   windows   enc   sub   rap   turn   reference   rect   

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.

boost propertyTree

标签:out   put   windows   enc   sub   rap   turn   reference   rect   

原文地址:https://www.cnblogs.com/sssblog/p/11116278.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!