HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

vector<tuple<A,B> > to map<A,B>

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
tuplemapvector

Problem

i have an vector > v and want to make a map from it
i came up with 3 variants:

std::transform(v.begin(),v.end(), std::inserter(map,map.begin()),[](std::tuple t){
    return std::make_pair(std::get(t),std::get(t));
});


 

std::for_each(v.begin(), v.end(), [](std::tuple t){
    map.insert(std::make_pair(std::get(t),std::get(t)));
});


 

for (auto t : v) {
    map.insert(std::make_pair(std::get(t),std::get(t)));
}


is shorter is better the way to go here? could one simplify the tuple=>pair conversion? thanks

Solution

I would use the last as the simplest, yes. I'd probably write a pair_from_tuple helper function to not have to write out the std::get explicitly.

The first and second both require you to write out the tuple type. This will change soon, but not everyone will immediately have C++14. Also, they're easier to get wrong; I think you mean to specify capture-by-reference in example 2, for example.

With pair_from_tuple, I suppose

using std::begin;
using std::end;
std::transform(begin(v), end(v), std::inserter{map, map.begin()}, pair_from_tuple);


would be okay (you can avoid the ` by making pair_from_tuple` a functor). Still less nice than

for (auto const& e : v)
    map.insert(pair_from_tuple(e));


, though.

Code Snippets

using std::begin;
using std::end;
std::transform(begin(v), end(v), std::inserter{map, map.begin()}, pair_from_tuple<int, char>);
for (auto const& e : v)
    map.insert(pair_from_tuple(e));

Context

StackExchange Code Review Q#31158, answer score: 4

Revisions (0)

No revisions yet.