How to iterate a boost property tree?

前端 未结 5 717
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-24 03:27

I am know approaching to boost property tree and saw that it is a good feature of boost libs for c++ programming.

Well, I have one doubt? how to iterate a property t

5条回答
  •  滥情空心
    2020-12-24 04:05

    I ran into this issue recently and found the answers incomplete for my need, so I came up with this short and sweet snippet:

    using boost::property_tree::ptree;
    
    void parse_tree(const ptree& pt, std::string key)
    {
      std::string nkey;
    
      if (!key.empty())
      {
        // The full-key/value pair for this node is
        // key / pt.data()
        // So do with it what you need
        nkey = key + ".";  // More work is involved if you use a different path separator
      }
    
      ptree::const_iterator end = pt.end();
      for (ptree::const_iterator it = pt.begin(); it != end; ++it)
      {
        parse_tree(it->second, nkey + it->first);
      }
    }
    

    Important to note is that any node, except the root node can contain data as well as child nodes. The if (!key.empty()) bit will get the data for all but the root node, we can also start building the path for the looping of the node's children if any.

    You'd start the parsing by calling parse_tree(root_node, "") and of course you need to do something inside this function to make it worth doing.

    If you are doing some parsing where you don't need the FULL path, simply remove the nkey variable and it's operations, and just pass it->first to the recursive function.

提交回复
热议问题