如何将std :: vector <boost :: shared_ptr <T >>复制到std :: list <T>

Joh*_*lin 1 c++ boost vector

std::list<KinBody::Link::Geometry> geometries = link->GetGeometries();
Run Code Online (Sandbox Code Playgroud)

该类型的link->GetGeometries()std::vector<boost::shared_ptr<Geometry>> ,我和上面的代码有以下错误.

error: conversion from ‘const std::vector<boost::shared_ptr<OpenRAVE::KinBody::Link::Geometry> >’ to     non-scalar type ‘std::list<OpenRAVE::KinBody::Link::Geometry>’ requested
std::list<KinBody::Link::Geometry> geometries = link->GetGeometries();
Run Code Online (Sandbox Code Playgroud)

我该怎么办 ?

lis*_*rus 7

std::list<KinBody::Link::Geometry> geometries;

for (auto const & p : link->GetGeometries())
    geometries.push_back(*p);
Run Code Online (Sandbox Code Playgroud)

对于for (auto const & p : ...)您需要启用C++ 11支持的部分(它使用自动类型推导和基于范围的for循环).

Pre-C++ 11等价于

std::list<KinBody::Link::Geometry> geometries;

typedef std::vector<boost::shared_ptr<KinBody::Link::Geometry>> geometries_vector_t;

geometries_vector_t const & g = link->GetGeometries();

for (geometries_vector_t::const_iterator i = g.begin(); i != g.end(); ++i)
    geometries.push_back(**i); // dereferencing twice: once for iterator, once for pointer
Run Code Online (Sandbox Code Playgroud)

注意:这一切看起来都很不自然.作为共享指针返回的对象意味着它KinBody::Link::Geometry实际上是基类或接口,或者此类型的对象很大,并且接口旨在避免大量复制或其他内容.我建议不要复制对象并将它们存储为接口建议的共享指针,除非您确实知道需要副本.