[英]Insert value to a std::map from a tuple
我只是在學習圖形的數據結構。我被困在這種情況下。
我寫過我的Graph
類
template <char... Args>
class Graph{};
其中char
類型的Args
表示我的Graph
的頂點。 但是,當我想在我的Graph中搜索時,我需要將每個char
頂點及其在Args
中的索引作為std::pair<char,size_t>
插入到std::map<char,size_t>
我有什么完成是我構建了一個std::tuple
類的
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
在std::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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.