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

标签 c++ boost vector

std::list<KinBody::Link::Geometry> geometries = link->GetGeometries();

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();

我该怎么办?

最佳答案

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

for (auto const & p : link->GetGeometries())
    geometries.push_back(*p);

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

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

注意:所有这些看起来都很不自然。作为共享指针返回的对象意味着 KinBody::Link::Geometry 实际上是一个基类或接口(interface),或者这种类型的对象很大并且接口(interface)旨在避免大量复制,或者其他什么别的。我建议不要像界面建议的那样复制对象并将它们存储为共享指针,除非你确实知道你需要这些拷贝。

关于c++ - 如何将 std::vector<boost::shared_ptr<T>> 复制到 std::list<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33076111/

相关文章:

c++ - Boost::Spirit::Qi - 将规则拆分为单独的类

c++ - 连通分量 BOOST c++

对向量进行舍入,以使所有结果元素都不同

c++ - map 中过期的 weak_ptr 会发生什么

c++ - GoogleTest 通过引用初始化

c++ - 在 C++ 中从文件末尾读取最有效的方法是什么? (解析文件中的最后 128 位)

c++ - 如何使用 c++ libboost 运行进程并获取其输出?

c++ - Gtest,等于对象

database - 结合地理空间索引的多维搜索

c++ - undefined symbol 引用但库已链接