繁体   English   中英

从shared_pointers的地图填充矢量

[英]Filling a vector from a map of shared_pointers

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

原始地图类型是:

std::map< std::string, boost::shared_ptr< Element > >

目的地矢量是:

std::vector< Element > theVector;

到目前为止我所拥有的是:

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

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

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

但它也没有用。

编辑:

我有这个有效的解决方案,但我觉得它不那么令人印象深刻:)

std::for_each( theMap.begin(), theMap.end(), 
        [&](map_type::value_type& pair)
        {
            theVector.push_back( *pair.second );
        } );

Edit2:我在这里不太熟悉的是bind(),所以欢迎bind()解决方案!

怎么样:

// 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上的在线演示。

另一种替代方法可能是新for语法:

for(auto &cur_pair: the_map) { theVector.push_back(*(cur_pair.second)); }

它至少是一个单行(有点),虽然它只是另一种方式来做你的std::for_each但更紧凑。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM