首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从shared_pointers地图填充矢量

从shared_pointers地图填充矢量
EN

Stack Overflow用户
提问于 2013-02-01 00:35:56
回答 2查看 543关注 0票数 4

我一直在尝试从地图中填充一个矢量。我知道如何以一种更传统的方式做到这一点,但我试图通过STL算法(单行)来实现它,作为某种训练:)。

源图类型为:

代码语言:javascript
复制
std::map< std::string, boost::shared_ptr< Element > >

目标向量为:

代码语言:javascript
复制
std::vector< Element > theVector;

到目前为止,我得到的是:

代码语言:javascript
复制
std::transform( theMap.begin(), theMap.end(),
        std::back_inserter( theVector ),
        boost::bind( &map_type::value_type::second_type::get, _1 )
        );

但这是试图在向量中插入一个指针,这是不起作用的。我也尝试过这个:

代码语言:javascript
复制
using namespace boost::lambda;
using boost::lambda::_1;

std::transform( theMap.begin(), theMap.end(),
        std::back_inserter( theVector ),
        boost::bind( &map_type::value_type::second_type::get, *_1 )
        );

但它也不起作用。

编辑:

我已经有了这个有效的解决方案,但我发现它不那么令人印象深刻:)

代码语言:javascript
复制
std::for_each( theMap.begin(), theMap.end(), 
        [&](map_type::value_type& pair)
        {
            theVector.push_back( *pair.second );
        } );

Edit2:这里我不太习惯使用bind(),所以欢迎使用bind()解决方案!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-02-01 01:15:09

另一种选择可能是新的for语法:

代码语言:javascript
复制
for(auto &cur_pair: the_map) { theVector.push_back(*(cur_pair.second)); }

它至少是一行代码(有点),虽然它只是std::for_each的另一种方式,但更紧凑。

票数 1
EN

Stack Overflow用户

发布于 2013-02-01 00:58:25

这样如何:

代码语言:javascript
复制
// Using std::shared_ptr and lambdas as the solution
// you posted used C++11 lambdas.
//
std::map<std::string, std::shared_ptr<Element>> m
    {
        { "hello", std::make_shared<Element>() },
        { "world", std::make_shared<Element>() }
    };
std::vector<Element> v;

std::transform(m.begin(),
               m.end(),
               std::back_inserter(v),
               [](decltype(*m.begin())& p) { return *p.second; });

请访问http://ideone.com/ao1C50查看在线演示。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14630667

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档