首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >巢式Boost.Assignment `map_list_of`

巢式Boost.Assignment `map_list_of`
EN

Stack Overflow用户
提问于 2012-09-19 10:52:23
回答 1查看 3K关注 0票数 3

是否可以更改此C++11初始化:

代码语言:javascript
复制
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,所以各种模板都是不确定的。

编辑:我想使用的“理想”包装界面如下所示:

代码语言:javascript
复制
//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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-19 11:22:42

以这种方式嵌套map_list_of是可能的,with hackery (但在下面可能有临时创建的,我对此不确定):

代码语言:javascript
复制
#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";

可能的宏接口(忽略空需求,主要是因为我不确定它的含义):

代码语言:javascript
复制
#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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12493277

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档