Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy map values to vector in STL

Working my way through Effective STL at the moment. Item 5 suggests that it's usually preferable to use range member functions to their single element counterparts. I currently wish to copy all the values in a map (i.e. - I don't need the keys) to a vector.

What is the cleanest way to do this?

like image 827
Gilad Naor Avatar asked Apr 21 '09 07:04

Gilad Naor


People also ask

Can we make vector of map in C++?

Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. Vector of Maps in STL: Vector of maps can be used to design complex and efficient data structures.


1 Answers

You could probably use std::transform for that purpose. I would maybe prefer Neils version though, depending on what is more readable.


Example by xtofl (see comments):

#include <map> #include <vector> #include <algorithm> #include <iostream>  template< typename tPair > struct second_t {     typename tPair::second_type operator()( const tPair& p ) const { return p.second; } };  template< typename tMap >  second_t< typename tMap::value_type > second( const tMap& m ) { return second_t< typename tMap::value_type >(); }   int main() {     std::map<int,bool> m;     m[0]=true;     m[1]=false;     //...     std::vector<bool> v;     std::transform( m.begin(), m.end(), std::back_inserter( v ), second(m) );     std::transform( m.begin(), m.end(), std::ostream_iterator<bool>( std::cout, ";" ), second(m) ); } 

Very generic, remember to give him credit if you find it useful.

like image 193
Skurmedel Avatar answered Oct 08 '22 00:10

Skurmedel