从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 );
} );
编辑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
但更紧凑。
相关文章:
- 在c++中用vector填充一个简单的动态数组
- 为什么不;名字在地图上是按顺序排列的吗
- 如何使用用户输入在C++中正确填充2D数组
- 基于多个条件处理地图中的所有元素
- 如何找到大小'x'数组是否完全填充,在C++?
- 在C++中将矢量转换为嵌套地图
- Cuda C++:设备上的Malloc类,并用来自主机的数据填充它
- 通过for循环使用用户输入填充列表
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 替换基于地图的所有引用
- 以不同的方式填充地图
- 如何破坏地图并在C 中填充地图指针
- 自动填充标准::地图
- 最易读(代码术语)的方式,用 C++03 中的构造数据填充地图<字符串、字符串>
- 在C++中填充地图容器时的多晶型设计
- 将矢量填充到地图中
- 如何在C++中填充 int 和矢量的地图<int>?
- 在全球范围内填充地图
- 从shared_pointers地图填充矢量
- 配对 cpp 或使用地图进行填充和打印