The compiler error is actually quite brief:
error: cannot convert 'std::pair<const std::basic_string<char>, int>' to 'int' in assignment
And that is exactly what the problem is. map you are copying has iterators that split into pair<KEY,VALUE> , and there is no way to implicitly convert pair<KEY,VALUE> to VALUE only.
Because of this, you cannot use copy or copy_if to copy from map to vector ; but the standard library provides an algorithm that you can use, creatively called transform . transform very similar to copy in that it accepts two source iterators and a destination iterator. The transform difference also accepts a unary function that performs the actual conversion. Using lambda C ++ 11, you can copy the entire contents of map to vector as follows:
transform( m.begin(), m.end(), back_inserter(v), [] (const MyMap::value_type& vt) { return vt.second; });
What if you do not want to copy the entire contents of the map , but only some elements that meet the certian criteria? Simple, just use transform_if .
What is it, you say? Is there no transform_if in the standard library? Well yes, you have a point there. Disappointing that there is no transform_if in the standard library. However, writing one is a fairly simple task. Here is 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 would expect, using transform_if like accepting copy_if and merging it with transform . Here are some psudo code to demonstrate:
transform_if( m.begin(), m.end(), back_inserter(v), [] (const MyMap::value_type& vt)