如何copy_if从地图到矢量? [英] How to copy_if from map to vector?

查看:127
本文介绍了如何copy_if从地图到矢量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将与地图< string,int> 中的谓词(等于int)匹配的值复制到向量< int> ;



这是我尝试的:

  #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& & it)
{
return(0 ==(it.second%2));
}
);
}

来自g ++ 4.6.1的错误消息是:

 错误:无法将转换中的'std :: pair< const std :: basic_string< char>,int>'转换为'int'有没有办法调整示例来做上面的复制?

=h2_lin>解决方案

使用 boost :: range 它很容易:

  boost :: push_back(
v,
m | boost :: adapters :: map_values
| boost :: adapters :: filtered int val){return 0 ==(val%2);}));


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); }));

这篇关于如何copy_if从地图到矢量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆