【问题标题】:Filling a vector from a map of shared_pointers从 shared_pointers 映射中填充向量
【发布时间】:2013-01-31 16:35:55
【问题描述】:

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

【问题讨论】:

  • 矢量 拥有 它是资源,shared_ptr 也是如此,因此在不复制的情况下移动是不可能的,但我想你不一定要从 shared_ptr 移动向量,但只是以优雅的方式复制。

标签: c++ boost stl


【解决方案1】:

怎么样:

// 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_each 解决方案。我正在寻找一个 bind() 解决方案,我认为这是可能的,但我可能错了
  • @foke 我同意,它与您在问题中的解决方案类似,但我想您确实知道 lambda 和 bind 都不会改变性能,而且很多时候 bind 更具可读性(@ 987654322@)
【解决方案2】:

另一种选择可能是新的for 语法:

for(auto &cur_pair: the_map) { theVector.push_back(*(cur_pair.second)); }

它至少是一个单线(有点),虽然它只是另一种处理 std::for_each 的方式,但更紧凑。

【讨论】:

  • 我没有考虑过这个;) 但我使用的是 vs 2010,我相信它不支持这种语法
  • 您是正确的,它在 2012 年受支持,但在 2010 年不受支持。请参阅此链接以获取 msdn 参考:msdn.microsoft.com/en-ca/library/vstudio/hh567368.aspx 在该列表中被称为“基于范围的 for 循环”,它确认现在是 2012 年,但不是 2010 年。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-18
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多