std::transform would be the most idiomatic way. You need a functional object:
template<typename PairType> struct Second { typename PairType::second_type operator()( PairType const& obj ) const { return obj.second; } }
(If you work a lot with std::map or other things that use std::pair , you will get this in your tool.)
After that, this is a little inconvenient because you only need the last n. since iterators in the map are not random access iterators, and you cannot add or subtract arbitrary values, the easiest solution is to copy them, then delete the ones you don't want:
std::vector<MyType> extractLastN( std::map<double, MyType> const& source, size_t n ) { std::vector<MyType> results; std::transform( source.begin(), source.end(), std::back_inserter( results ), Second<std::map<double, MyType>::value_type>() ); if ( results.size() > n ) { results.erase( results.begin(), results.end() - n ); } return results; }
This is not the most efficient, but depending on n and where it might be enough. If you want to avoid additional copying, etc. (probably worth it only if n usually much smaller than the size of the map), you will need to do something more pleasant:
std::vector<MyType> extractLastN( std::map<double, MyType> const& source, ptrdiff_t n ) { std::map<double, MyType>::const_iterator start = source.size() <= n ? source.begin() : std::prev( source.end(), n ); std::vector<MyType> results; std::transform( start, source.end(), std::back_inserter( results ), Second<std::map<double, MyType>::value_type>() ); return results; }
(If you don't have access to C ++ 11, std::prev simply:
template<typename IteratorType> IteratorType prev( IteratorType start, ptrdiff_t n ) { std::advance( start, -n ); return start; }
Again, if you work a lot with the standard library, you probably already have it in your toolbox.)