从shared_pointers地图填充矢量

Filling a vector from a map of shared_pointers

本文关键字:填充 地图 pointers shared      更新时间:2023-10-16

我一直在尝试从地图中填充向量。我知道如何以更传统的方式做到这一点,但我试图用 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 );
        } );

编辑2:我不太喜欢的是 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但更紧凑。