从 Boost 属性树中提取 STL 映射 [英] Extracting STL Map from Boost Property Tree
问题描述
我知道 boost::property_tree::ptree
可能包含键值对,其中值"可以是任何类型.现在我的问题是,现在我的值"是 std::map
,当我尝试 pt.get<std::map<std::string, std::string>>
其中 pt
是属性树,我收到编译时错误.因此,我的问题是:
I understand that boost::property_tree::ptree
may contain key-value pairs where the 'value' may be of any type. Now my question is that, now my 'value' is a std::map
, and when I attempt to pt.get<std::map<std::string, std::string>>
where pt
is a property tree, I get a compile time error. Hence, my question is:
如何从 boost 属性树中提取 STL 映射值?如果不行,有没有办法在STL map和boost属性树之间进行转换(这样属性树的每个节点都不是STL容器而是一个简单的数据类型).
推荐答案
很简单:
ptree pt;
std::map<std::string, ptree> m(pt.begin(), pt.end());
但是,请注意键不必是唯一的:
However, note that keys need not be unique:
std::multimap<std::string, ptree> mm(pt.begin(), pt.end());
如果您想将所有值转换为 std::string
(假设它们都有一个字符串值):
And if you are want to transform all values to std::string
(assuming they all have a string value):
std::map<std::string, std::string> dict;
for (auto& [k,v]: pt) {
dict.emplace(k, v.get_value<std::string>());
}
并排比较
#include <boost/property_tree/ptree.hpp>
#include <map>
#include <fmt/ranges.h>
using boost::property_tree::ptree;
template<> struct fmt::formatter<ptree> : fmt::formatter<std::string>
{
template<typename Ctx>
auto format(ptree const& pt, Ctx& ctx) {
return format_to(ctx.out(), "'{}'", pt.get_value<std::string>());
}
};
int main() {
ptree pt;
pt.put("keyA", "valueA-1");
pt.put("keyB", "valueB");
pt.put("keyC", "valueC");
pt.add("keyA", "valueA-2"); // not replacing same key
std::map<std::string, ptree> m(pt.begin(), pt.end());
std::multimap<std::string, ptree> mm(pt.begin(), pt.end());
std::map<std::string, std::string> dict;
for (auto& [k,v]: pt) {
dict.emplace(k, v.get_value<std::string>());
}
fmt::print(
"map:\n\t{}\n"
"multimap:\n\t{}\n"
"dict:\n\t{}\n",
fmt::join(m, "\n\t"),
fmt::join(mm, "\n\t"),
fmt::join(dict, "\n\t")
);
}
印刷品
map:
("keyA", 'valueA-1')
("keyB", 'valueB')
("keyC", 'valueC')
multimap:
("keyA", 'valueA-1')
("keyA", 'valueA-2')
("keyB", 'valueB')
("keyC", 'valueC')
dict:
("keyA", "valueA-1")
("keyB", "valueB")
("keyC", "valueC")
奖励:来自字符串字典的 Ptree
template <typename MapLike>
ptree ptree_from_map(MapLike const& m) {
ptree pt;
for (auto const& [k,v]: m) {
pt.add(k, v);
}
return pt;
}
这篇关于从 Boost 属性树中提取 STL 映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!