The compiler error is actually quite succinct:
error: cannot convert 'std::pair<const std::basic_string<char>, int>' to 'int' in assignment
And that's exactly what the problem is. The map
you're copying from has iterators that dereference to a pair<KEY,VALUE>
, and there's no way to implicitly transform a pair<KEY,VALUE>
to just a VALUE
.
Because of this, you can't use copy
or copy_if
to copy from a map
to a vector
; but the Standard Library does provide an algorithm you can use, creatively called transform
. transform
is very similar to copy
in that it takes two source iterators and a destination iterator. The difference is transform
also takes a unary function that does the actual transformation. Using a C++11 lambda, you can copy the entire contents of a map
to a vector
like this:
transform( m.begin(), m.end(), back_inserter(v), [] (const MyMap::value_type& vt)
{
return vt.second;
});
What if you don't want to copy the entire contents of the map
, but only some elements meeting certian criteria? Simple, just use transform_if
.
What's that, you say? There is no transform_if
in the Standard Library? Well yeah, you do have a point there. Frustratingly, there is no transform_if
in the Standard Library. However writing one is a simple enough task. Here's the code:
template<class InputIterator, class OutputIterator, class UnaryFunction, class Predicate>
OutputIterator transform_if(InputIterator first,
InputIterator last,
OutputIterator result,
UnaryFunction f,
Predicate pred)
{
for (; first != last; ++first)
{
if( pred(*first) )
*result++ = f(*first);
}
return result;
}
As you might expect, using transform_if
is like taking copy_if
and mashing it together with transform
. Here's some psudo-code to demonstrate:
transform_if( m.begin(), m.end(), back_inserter(v),
[] (const MyMap::value_type& vt) // The UnaryFunction takes a pair<K,V> and returns a V
{
return vt.second;
}, [] (const MyMap::value_type& vt) // The predicate returns true if this item should be copied
{
return 0 == (vt.second%2);
} );