【问题标题】:Insert value to a std::map from a tuple从元组向 std::map 插入值
【发布时间】:2018-05-23 15:11:32
【问题描述】:

我只是在学习图的数据结构。我被困在这种情况下。
我已经写了我的Graph 类,比如

template <char... Args>
    class Graph{}; 

其中char 类型的Args 表示我的Graph 的顶点。 但是,当我想在我的图表中搜索时,我需要将char 的每个顶点及其在Args 中的索引作为std::pair&lt;char,size_t&gt; 插入std::map&lt;char,size_t&gt;。我所做的是我构造了一个@987654330 @点赞

 std::tuple<decltype(Args)...> t(Args...);

那我就想做这样的

 for(size_t i =0;i<sizeof...(Args);++i)
      Map.insert({0,std::get<i>(t)});

哪个 Map 表示std::map&lt;size_t,char&gt;。 它肯定不起作用,因为std::get&lt;&gt; 中使用的i 不是constexpr。 我现在能做的就是像

一样一一插入到地图中
Map.insert({0,std::get<0>(t)});
Map.insert({1,std::get<1>(t)});
Map.insert({2,std::get<2>(t)});

但这不是我想要的结果。那么还有其他适合我的解决方案吗?
感谢您的帮助!

【问题讨论】:

    标签: c++ c++11 stdmap stdtuple


    【解决方案1】:

    std::map&lt;char,size_t&gt;std::map&lt;size_t,char&gt;?
    我会选择std::map&lt;size_t,char&gt;

    你需要 C++14 的 std::index_sequence1

    template <char... Chars, std::size_t... Ints>
    void fill_map(std::map<size_t, char> & your_map, std::index_sequence<Ints...>) {
        using swallow = int[];
        (void)swallow{0, (your_map.emplace(Ints, Chars), 0)... };
    }
    
    template <char... Chars>
    void fill_map(std::map<size_t, char> & your_map) {
        fill_map<Chars...>(your_map, std::make_index_sequence<sizeof...(Chars)>{});
    }
    

    使用:

    std::map<size_t,char> your_map;
    fill_map<Args...>(your_map);
    


    1implementation for C++11

    【讨论】:

    • 谢谢!这正是我所需要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    相关资源
    最近更新 更多