How to copy_if from map to vector?

Posted by VJo on Stack Overflow See other posts from Stack Overflow or by VJo
Published on 2011-11-15T14:28:17Z Indexed on 2011/11/16 1:50 UTC
Read the original article Hit count: 177

Filed under:
|
|

I'd like to copy values that match a predicate (equal ints) from a map<string,int> to a vector<int>.

This is what I tried:

#include <map>
#include <vector>
#include <algorithm>

int main()
{
    std::vector< int > v;
    std::map< std::string, int > m;

    m[ "1" ] = 1;
    m[ "2" ] = 2;
    m[ "3" ] = 3;
    m[ "4" ] = 4;
    m[ "5" ] = 5;

    std::copy_if( m.begin(), m.end(), v.begin(),
                  [] ( const std::pair< std::string,int > &it )
                  {
                    return ( 0 == ( it.second % 2 ) );
                  }
                  );
}

The error message from g++ 4.6.1 is :

error: cannot convert 'std::pair<const std::basic_string<char>, int>' to 'int' in assignment

Is there a way to adjust the example to do the above copy?

© Stack Overflow or respective owner

Related posts about c++

Related posts about copy