c++ - 从 shared_pointers 映射中填充 vector

标签 c++ boost stl

我一直在尝试从 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/

相关文章:

c++ - 为什么 std::pair<A,B> 与 std::tuple<A,B> 不同? (真的没有办法吗?)

c++ - 在 linux 中使用两个进程读取文件?

c++ - 如何使用 C++ 加密文件夹?

c++ - boost 线程 pthread_mutex_lock 问题

c++ - 为什么在 Windows 上没有微秒分辨率的 boost::date_time?

c++ - 如何在此多重集上设置两种比较器(一种用于插入,一种用于查找)?

c++ - QLabel 将全尺寸放入 QToolBar

c++ - QGraphicsItem 自定义类-> type() 不起作用

python - Boost Python,Visual Studio 链接到错误的 boost dll

c++ - `std::set` 有什么问题?