C++ C++;:嵌套映射
定义如下:C++ C++;:嵌套映射,c++,boost,map,nested,boost-variant,C++,Boost,Map,Nested,Boost Variant,定义如下: struct-nmap; 结构nmap:map{} 下面的最后一行不起作用: nmap my\u map; 我的地图[“a”]=“b”; 我的地图[“c”]=新的nmap; 我的地图[“c”][“d”]=“e” 我需要添加什么才能使其正常工作?我建议您选择一个小小的可读助手: #include <boost/variant.hpp> #include <map> using std::map; struct nmap; struct nmap: map&l
struct-nmap;
结构nmap:map{}代码>
下面的最后一行不起作用:
nmap my\u map;
我的地图[“a”]=“b”;
我的地图[“c”]=新的nmap;
我的地图[“c”][“d”]=“e”代码>
我需要添加什么才能使其正常工作?我建议您选择一个小小的可读助手:
#include <boost/variant.hpp>
#include <map>
using std::map;
struct nmap;
struct nmap: map<std::string, boost::variant<std::string, nmap*>>
{
typedef boost::variant<std::string, nmap*> Variant;
typedef map<std::string, Variant> base;
friend nmap& as_map(Variant& v) { return *boost::get<nmap*>(v); }
friend nmap const& as_map(Variant const& v) { return *boost::get<nmap*>(v); }
friend std::string& as_string(Variant& v) { return boost::get<std::string>(v); }
friend std::string const& as_string(Variant const& v) { return boost::get<std::string>(v); }
};
int main()
{
nmap my_map;
my_map["a"] = "b";
my_map["c"] = new nmap;
as_map(my_map["c"])["d"] = "e";
}
查看它
输出:
# g++ -std=c++11 -Wall -pedantic -Wextra main.cpp && ./a.out
{
a: b
c: {
d: e
f: {
empty: {}
most nested: leaf node
}
}
}
试试(*我的地图[“c”])[“d”]=“e”代码>可能?好的,试试(*boost::get(my_map[“c”]))[“d”]=“e”代码>@KerrekSB我会查一下的。如果没有boost::variant,我能做到这一点吗?很难说,但直觉告诉我们,您的实际问题可能有一个更好的解决方案…@KerrekSB no go。错误C2107:非法索引,不允许间接寻址添加了一个基于Boost递归变量的演示,展示了如何实现运算符这很漂亮。你不知道(你可能真的)我从这个答案中学到了多少!非常感谢。我在搜索变量值类型的嵌套字典(即map
)的良好实现时找到了这个答案。虽然这里描述的实现适用于容器(boost::variant visitor ideom)上的迭代访问,但容器上的随机访问似乎是不可能的。“有什么办法可以让这一切顺利进行吗?”mzoll当然要付出代价。例如,使用向量
static std::ostream& operator<<(std::ostream& os, nmap const& map)
{
struct print : boost::static_visitor<void>
{
print(std::ostream& os, int indent = 0) : os(os), indent(indent) { }
void operator()(map_t const& map) const {
os << "{";
for(auto& item : map)
{
os << "\n";
do_indent();
os << " " << item.first << ": ";
boost::apply_visitor(print(os, indent+4), item.second);
}
if (!map.empty()) { os << "\n"; do_indent(); };
os << "}";
}
void operator()(std::string const& str) const {
os << str;
}
private:
std::ostream& os;
void do_indent() const { for (int n = indent; n>0; --n) os << ' '; }
int indent = 0;
};
boost::apply_visitor(print(os), map);
return os;
}
# g++ -std=c++11 -Wall -pedantic -Wextra main.cpp && ./a.out
{
a: b
c: {
d: e
f: {
empty: {}
most nested: leaf node
}
}
}