c++ - 从元组向 std::map 插入值
问题描述
我只是在学习图的数据结构。我被困在这种情况下。
我写我的Graph
课就像
template <char... Args>
class Graph{};
其中Args
of 类型char
表示 my 的顶点Graph
。但是,当我想在我的图表中搜索时,我需要将每个顶点char
及其索引Args
作为 astd::pair<char,size_t>
插入到 astd::map<char,size_t>
中。我所做的是我构造了一个std::tuple
like
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)});
但这不是我想要的结果。那么还有其他适合我的解决方案吗?
谢谢你的帮助!
解决方案
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 个 实现。
推荐阅读
- python - 将 YUV 导入为字节数组
- dart - 如何使用 dartanalyzer AnalysisContext 分析新来源?
- python - 将 ecdf 函数应用于数据框中的每一列并绘图
- android - ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION},REQ_LOC);:ERROR:-无法解析 REQ_LOC
- sql - 如何在 Postgres 中使用 CASE 或 IF 语句从不同的表中进行选择?
- javascript - 在 CRM 上运行应用程序时出现 javascript 错误
- ionic2 - 如何检测我的应用程序是通过 URL(深度链接)打开还是在 ionic 2 中正常启动?
- loops - 循环遍历两个列表
- javascript - 记住设备并重新连接
- css - 如何最大化。使用 flexbox 每行 8 个项目?