c++中map的简写语法
shorthand syntax for c++ map in map
如果我有如下定义:
typedef map<string, Foo> Foo_map_1
typedef map<string, Foo_map_1> Foo_map_2
typedef map<string, Foo_map_2> Foo_map_3
typedef map<string, Foo_map_3> Foo_map_4
typedef map<string, Foo_map_4> Foo_map_5
我能不能概括一下,比如,
Foo_map<10>
并有一个10倍嵌套映射。我不需要boost::recursive_wrapper
这样的东西因为层数总是恒定的
即使对于有限的c++元编程能力来说,这似乎也很容易:
#include <map>
#include <string>
template<int N, typename K, typename V>
struct NMap { typedef std::map<K, typename NMap<N-1, K, V>::type> type; };
template<typename K, typename V>
struct NMap<1, K, V> { typedef std::map<K, V> type; };
int main(int argc, const char *argv[]) {
NMap<3, int, std::string>::type m;
m[1][2][3] = "Test";
return 0;
}
这对我很有用。
#include <iostream>
#include <string>
#include <map>
using namespace std;
struct Foo
{
Foo() : _in(0) {}
Foo(int in) : _in(in) {}
int _in;
};
template <int N> struct Foo_map
{
map<string, Foo_map<N-1> > foo_Map;
Foo_map<N-1>& operator[](string const& key) { return foo_Map[key]; }
};
template <> struct Foo_map<1>
{
map<string, Foo> foo_Map;
Foo& operator[](string const& key) { return foo_Map[key]; }
};
int main()
{
Foo_map<1> map1;
map1["abcd"] = Foo(10);
Foo_map<2> map2;
map2["a"]["b"] = Foo(20);
Foo_map<10> map10;
map10["a"]["b"]["c"]["d"]["e"]["f"]["g"]["h"]["i"]["j"] = Foo(100);
std::cout << map1["abcd"]._in << std::endl;
std::cout << map2["a"]["b"]._in << std::endl;
std::cout << map10["a"]["b"]["c"]["d"]["e"]["f"]["g"]["h"]["i"]["j"]._in << std::endl;
}
运行程序的输出:
<>之前1020.One hundred.相关文章:
- 1d 智能指针不适用于语法 (*)++
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 助记符和指向成员语法的指针
- 有人能分解一下这个c++模板的语法吗
- C++避免重复声明的语法是什么
- QMetaObject invokeMethod的基于函数指针的语法
- 使用一个考虑到std::map中键值的滚动或换行的键
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 允许从 std::map 的密钥窃取资源?
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将强制转换运算符重载到 std::map 的正确语法是什么
- 无法让 Boost Spirit 语法使用 std::map 的已知键<>
- 使用自定义对象的地图使用MAP?可能是语法问题
- 错误 C2061:语法错误:标识符'map'
- 通过std::unique_ptr使用std::map访问操作符[]的正确语法
- c++中map的简写语法
- 从std::set或std::map继承初始化语法