是否可以更改此C++11初始化:
const std::map<int, std::map<int, std::string>> test =
{{1,
{{1, "bla"},
{2, "blie"}
}
},
{3,
{{1, "ha"},
{2, "hie"}
}
}
};在不使用临时程序的情况下使用Boost.Assignment?不幸的是,以这种方式嵌套map_list_of似乎是不可能的。我说错了吗?
注意:我已经为一些可怕的宏做好了准备。只要它能正常工作,就可以了。由于目标编译器是Intel C++ 2013和/或MSVS2012,所以各种模板都是不确定的。
编辑:我想使用的“理想”包装界面如下所示:
//header
extern const std::map<int, std::map<int, std::string>> test;
// source file
/*something*/ test
/*something*/ 1,
/*something*/ 1, "bla" /*something*/
/*something*/ 2, "blie" /*something*/
/*something*/ 2 //etc...任何/*something*/都可以是空的。这应该同时使用C++11大括号init或boost::assign::map_list_of。我试图避免像这里这样的手动重复:https://stackoverflow.com/a/1872506/256138
发布于 2012-09-19 11:22:42
以这种方式嵌套map_list_of是可能的,with hackery (但在下面可能有临时创建的,我对此不确定):
#include <map>
#include <string>
#include <boost/assign/list_of.hpp>
using boost::assign::map_list_of;
const std::map<int, std::map<int, std::string> > test =
map_list_of
(1, map_list_of
(1, "bla")
(2, "blie")
.convert_to_container<std::map<int, std::string> >()
)
(3, map_list_of
(1, "ha")
(2, "hie")
.convert_to_container<std::map<int, std::string> >()
)
;
// Correctly prints "hie".
//std::cout << test.find(3)->second.find(2)->second << "\n";可能的宏接口(忽略空需求,主要是因为我不确定它的含义):
#include <iostream>
#include <string>
#include <map>
#ifdef CPP_11_AVAILABLE // Unsure what the actual macro is.
#define map_entries_begin {
#define map_entries_end }
#define map_entry_begin {
#define map_entry_end },
#else
#include <boost/assign/list_of.hpp>
#define map_entries_begin boost::assign::map_list_of
#define map_entries_end
#define map_entry_begin (
#define map_entry_end )
#endif
const std::map<int, std::map<int, std::string>> test =
map_entries_begin
//------//
map_entry_begin
1, map_entries_begin
map_entry_begin 1, "bla" map_entry_end
map_entry_begin 2, "blie" map_entry_end
map_entries_end
map_entry_end
//------//
map_entry_begin
3, map_entries_begin
map_entry_begin 1, "ha" map_entry_end
map_entry_begin 2, "hie" map_entry_end
map_entries_end
map_entry_end
map_entries_end;
int main()
{
std::cout << test.find(3)->second.find(2)->second << "\n";
return 0;
}诚然相当冗长,但似乎符合你的要求。
参见C++11在线演示在http://ideone.com/6Xx2t。
https://stackoverflow.com/questions/12493277
复制相似问题