我一直在试图从地图中填充矢量。 我知道如何以更传统的方式做到这一点,但我试图用STL算法(一个班轮)作为某种训练来实现它:)。从shared_pointers的地图中填充矢量
起源地图类型是:
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()解决方案是受欢迎的!
Vector _owns_它是资源,所以shared_ptr也是如此,因此在不复制副本的情况下移动在这里是没有问题的,但我想你不一定要从shared_ptr移动到vector,而只是为了以优雅的方式复制。 – legends2k
是的,我想要一个副本 – foke