![](/img/trans.png)
[英]Initializing boost::shared_ptr<std::vector<T>> with boost::shared_ptr<std::list<T>>
[英]How to copy std::vector<boost::shared_ptr<T>> to std::list<T>
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
實際上是基類或接口,或者該類型的對象很大,並且該接口旨在避免大量復制或其他操作。 我建議不要復制對象,也不要像接口所建議的那樣將它們存儲為共享指針,除非您實際上知道需要復制。
既然您提到了增強功能,那么讓我向您展示一些增強范圍糖。
link->getgeometries() | adaptors::indirected
這將導致包含Geometry&
元素的范圍。 用copy_range
填充列表:
geometries = boost::copy_range<std::list<link::geometry>>(
link->getgeometries() | adaptors::indirected
);
觀看完整的演示:
#include <boost/range/algorithm.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/make_shared.hpp>
#include <iostream>
namespace KinBody {
struct Link {
struct Geometry {};
std::vector<boost::shared_ptr<Geometry> > GetGeometries() const {
return {};
}
};
}
int main() {
using namespace boost;
using namespace KinBody;
auto link = make_shared<Link>();
auto geometries = boost::copy_range<std::list<Link::Geometry>>(
link->GetGeometries() | adaptors::indirected
);
}
線
std::list<KinBody::Link::Geometry> geometries = link->GetGeometries();
嘗試將向量分配給列表。 編譯器告訴您您不能這樣做。 您要做的是迭代向量並將每個元素插入列表。
請注意,向量包含指向幾何的共享指針,而列表被聲明為包含實例。 如果要將指針存儲在列表中,則必須將其聲明為:
std::list<KinBody::Link::Geometry*> // note the *
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.