Filling a vector from a shared_pointers map

I am trying to fill a vector from a map. I know how to do this in a more ordinary way, but I tried to achieve it using the STL algorithms (one liner) as a kind of training :).

type of card origin:

std::map< std::string, boost::shared_ptr< Element > > 

destination vector:

 std::vector< Element > theVector; 

what i have so far:

 std::transform( theMap.begin(), theMap.end(), std::back_inserter( theVector ), boost::bind( &map_type::value_type::second_type::get, _1 ) ); 

But this is an attempt to insert a pointer into a vector that does not work. I 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 doesn’t work either.

Edit:

I have 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: What I'm less comfortable with here is bind (), so bind () requests are welcome!

+4
source share
2 answers

Another alternative might be the new for syntax:

 for(auto &cur_pair: the_map) { theVector.push_back(*(cur_pair.second)); } 

This is at least one-line (kinda), although this is just another way to make your std::for_each , but more compact.

+1
source

What 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; }); 

Watch the online demo at http://ideone.com/ao1C50 .

+2
source

All Articles