Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy_if from map to vector?

Tags:

c++

copy

c++11

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?

like image 576
BЈовић Avatar asked Nov 15 '11 14:11

BЈовић


1 Answers

With boost::range it is as easy as:

boost::push_back(
    v,
    m | boost::adaptors::map_values 
      | boost::adaptors::filtered([](int val){ return 0 == (val % 2); }));
like image 153
Mankarse Avatar answered Oct 05 '22 11:10

Mankarse