我一直在尝试从 map 中填充 vector 。 我知道如何以更传统的方式做到这一点,但我试图用 STL 算法(一个衬里)来实现它作为某种训练:)。
原始 map 类型是:
std::map< std::string, boost::shared_ptr< Element > >
目标 vector 是:
std::vector< Element > theVector;
我目前的情况是这样的:
std::transform( theMap.begin(), theMap.end(),
std::back_inserter( theVector ),
boost::bind( &map_type::value_type::second_type::get, _1 )
);
但是这是试图在 vector 中插入一个指针,但这是行不通的。 我也试过这个:
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 .
关于c++ - 从 shared_pointers 映射中填充 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14630667/