我一直在尝试从地图中填充一个矢量。我知道如何以一种更传统的方式做到这一点,但我试图通过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()解决方案!
发布于 2013-02-01 01:15:09
另一种选择可能是新的for语法:
for(auto &cur_pair: the_map) { theVector.push_back(*(cur_pair.second)); }它至少是一行代码(有点),虽然它只是std::for_each的另一种方式,但更紧凑。
发布于 2013-02-01 00:58:25
这样如何:
// 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查看在线演示。
https://stackoverflow.com/questions/14630667
复制相似问题