Code Review Asked by Valerij on January 25, 2021
i have an vector<tuple<A,b> > v
and want to make a map<A,B>
from it
i came up with 3 variants:
std::transform(v.begin(),v.end(), std::inserter(map,map.begin()),[](std::tuple<int,char> t){
return std::make_pair(std::get<0>(t),std::get<1>(t));
});
std::for_each(v.begin(), v.end(), [](std::tuple<int,char> t){
map.insert(std::make_pair(std::get<0>(t),std::get<1>(t)));
});
for (auto t : v) {
map.insert(std::make_pair(std::get<0>(t),std::get<1>(t)));
}
is shorter is better
the way to go here? could one simplify the tuple
=>pair
conversion? thanks
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<int, char>);
would be okay (you can avoid the <int, char>
by making pair_from_tuple
a functor). Still less nice than
for (auto const& e : v)
map.insert(pair_from_tuple(e));
, though.
Answered by Anton Golov on January 25, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP