这是我第一次使用boost::property_tree,我找不到一种方法来按照文档(How to Access Data in a Property Tree)从树中获取值。这是我为试验属性树而编写的简单代码:
#include <iostream>
#include <string>
#include <boost/property_tree/info_parser.hpp>
#include <boost/property_tree/ptree.hpp>
namespace pt = boost::property_tree;
int main(int argc, char *argv[]) {
pt::ptree tree;
tree.put("pi", 3.14159);
tree.put("name", "John Doe");
for (auto &[key, value] : tree)
std::cout << key << " : " << value.get_value<std::string>() << "\n";
std::cout << "pi : " << tree.get_value("pi") << "\n";
std::cout << "name : " << tree.get_value("name") << "\n";
auto pi = tree.get_optional<float>("pi").get();
std::cout << "pi optional : " << pi << "\n";
auto pi_found = tree.find("pi");
std::cout << "pi found : " << pi_found->second.data() << "\n";
// the commented line doesn't compile
// std::cout << "not found : " << tree.get_value<int>("null") << "\n";
std::cout << "not found : " << tree.get_value("null") << "\n";
// the line below causes an assertion error:
// Assertion failed: (this->is_initialized()), function get, file /usr/local/include/boost/optional/optional.hpp, line 1191.
// not found : Abort trap: 6
std::cout << "not found : " << tree.get_optional<int>("null").get() << "\n";
pt::write_info("ptree.info", tree);
return 0;
}这是输出:
pi : 3.1415899999999999
name : John Doe
pi :
name :
pi optional : 3.14159
pi found : 3.1415899999999999
not found :可以看出,tree.get_value("whatever")不返回值,tree.get_value("null")不会抛出异常,get_optional<whatever type>也不会编译。我的实验行为与文档中所述的太不同了。排除导致断言错误的行将按预期创建输出信息文件。
我的环境是:
MacOS 10.11.6
macbrew installed tools and libraries
boost 1.67
clang 7.0
meson build system发布于 2018-09-26 01:17:26
您可以将ptree绘制为:
node1 is tree (has 2 children, data() of tree is "")
|
|- (node2) pi ----> data=3.14...
|
|- (node3) name --> data="Joe Doe"1
可以看到,tree.get_value(“
”)不返回值
tree是节点,有两个子节点(pi,name)。在调用
tree.get_value(defaultValue) // you are not passing PATH, but DEFAULT VALUE上面的行被翻译成
tree.get_child("").get_value(defaultValue)因此,""路径之所以存在,是因为它是指向tree节点的路径,并且tree.data()为该路径返回"" -空字符串。因此defaultValue不能打印,您会看到输出为空字符串。应该只针对子代调用get_value (在调用该methid之前,请在tree上使用get_child,boost参考中对此进行了说明),get_value的参数为默认值。所以替换掉
std::cout << "pi : " << tree.get_child("pi").get_value("PI is 4.0") << "\n";
std::cout << "name : " << tree.get_child("name").get_value("noname") << "\n";您将看到3.14和Joe Doe。
2
tree.get_value("null")不抛出异常
is在1点中被描述。""路径存在,此路径的data()为空字符串。因此您看不到null字符串作为默认值。
3.
//注释行不能编译// std::cout << "not found:“
<< tree.get_value("null") << "\n";
这行代码不能编译,因为ptree类没有这个方法,我想你应该调用这个方法:
template<typename Type>
unspecified get_value(const Type & default_value) const;您将Type定义为int,将int定义为函数模板参数涉及到默认值只能为int,不能为string。
发布于 2018-09-26 01:53:42
我的错是,我没有使用tree.get<float>("pi"),而是复制并粘贴了另一个用途的tree.get_value<float>("pi")。这个问题在@rafix07评论的帮助下得到了回答。get<type>("key path")是要使用的正确方法。
https://stackoverflow.com/questions/52502090
复制相似问题