首页 > 解决方案 > 从元组向 std::map 插入值

问题描述

我只是在学习图的数据结构。我被困在这种情况下。
我写我的Graph课就像

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

其中Argsof 类型char表示 my 的顶点Graph。但是,当我想在我的图表中搜索时,我需要将每个顶点char及其索引Args作为 astd::pair<char,size_t>插入到 astd::map<char,size_t>中。我所做的是我构造了一个std::tuplelike

 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<size_t,char>. 它当然不起作用,因为i使用的 instd::get<>不是constexpr. 我现在能做的是像一张一张地插入地图

Map.insert({0,std::get<0>(t)});
Map.insert({1,std::get<1>(t)});
Map.insert({2,std::get<2>(t)});

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

标签: c++c++11stdmapstdtuple

解决方案


std::map<char,size_t>还是std::map<size_t,char>
我会去的std::map<size_t,char>

您需要 C++14 的std::index_sequence 1

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);


C++11 的1 个 实现


推荐阅读