简体   繁体   中英

Insert value to a std::map from a tuple

I am just learning data structure of graph.And i'm trapped in such a situation.
I have written my Graph class like

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

where the Args of type char means the vertex of my Graph . However, when i want to search in my Graph,i need to insert each vertex of char and its index in Args as a std::pair<char,size_t> into a std::map<char,size_t> .What i have done is that i constructed a std::tuple like

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

Then i want to do like this

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

which Map means a std::map<size_t,char> . It certainly doesn't work because the i used in std::get<> is not a constexpr . What can i do now is to insert into the Map one by one like

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

But it is not the result i want.So are there any other solutions for me?
Thanks for any help!

std::map<char,size_t> or std::map<size_t,char> ?
I'll go with std::map<size_t,char> .

You need C++14's 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)>{});
}

use:

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


1 implementation for C++11 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM