I have been trying to fill a vector from a map. I know how to do this in a more conventional way, but I was trying to achive it with STL algorithms (a one liner) as some kind of a training :).
the origin map type is :
std::map< std::string, boost::shared_ptr< Element > >
the destination vector is :
std::vector< Element > theVector;
what I have so far is this:
std::transform( theMap.begin(), theMap.end(),
std::back_inserter( theVector ),
boost::bind( &map_type::value_type::second_type::get, _1 )
);
But this is trying to insert a pointer in the vector which doesn't work. I have also tried this:
using namespace boost::lambda;
using boost::lambda::_1;
std::transform( theMap.begin(), theMap.end(),
std::back_inserter( theVector ),
boost::bind( &map_type::value_type::second_type::get, *_1 )
);
But it's not working either.
Edit:
I've got this working solution but I find it less impressive :)
std::for_each( theMap.begin(), theMap.end(),
[&](map_type::value_type& pair)
{
theVector.push_back( *pair.second );
} );
Edit2: The thing I'm the less comfortable with here is bind(), so bind() solutions are welcome!
How about:
// Using std::shared_ptr and lambdas as the solution
// you posted used C++11 lambdas.
//
std::map<std::string, std::shared_ptr<Element>> m
{
{ "hello", std::make_shared<Element>() },
{ "world", std::make_shared<Element>() }
};
std::vector<Element> v;
std::transform(m.begin(),
m.end(),
std::back_inserter(v),
[](decltype(*m.begin())& p) { return *p.second; });
See online demo at http://ideone.com/ao1C50 .
Another alternative may be the new for
syntax:
for(auto &cur_pair: the_map) { theVector.push_back(*(cur_pair.second)); }
It's at least a one-liner (kinda), though it's just another way to do your std::for_each
but more compact.
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.