gpt4 book ai didi

c++ - 嵌套 Boost.Assignment `map_list_of`

转载 作者:太空狗 更新时间:2023-10-29 21:04:00 25 4
gpt4 key购买 nike

是否可以更改此 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 大括号初始化或 boost::assign::map_list_of。我试图避免像这里这样的手动重复:https://stackoverflow.com/a/1872506/256138

最佳答案

以这种方式嵌套 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";

可能的宏接口(interface)(忽略empty要求,主要是因为我不确定它是什么意思):

#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 .

关于c++ - 嵌套 Boost.Assignment `map_list_of`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12493277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com