patterncppMinor
vector<tuple<A,B> > to map<A,B>
Viewed 0 times
tuplemapvector
Problem
i have an
i came up with 3 variants:
is
vector > v and want to make a map from iti 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? thanksSolution
I would use the last as the simplest, yes. I'd probably write a
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
would be okay (you can avoid the `
, though.
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 supposeusing 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 thanfor (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.