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?
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); }));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With