[英]Transforming a vector<std::unique_ptr<A>> to vector<A>
There is a vector of std::unique_ptr<A>
.有一个
std::unique_ptr<A>
向量。 I need to pass that data to a function that expects a vector of A
.我需要将该数据传递给一个需要
A
向量的函数。
I tried using std::transform
, like this:我尝试使用
std::transform
,如下所示:
std::vector<std::unique_ptr<A>> a;
std::vector<A> aDirect;
std::transform(a.begin(), a.end(),
std::back_inserter(aDirect),
[](std::unique_ptr<A> element)-> A { return *element; });
but it seems that std::transform
tries to copy elements of a
at some point, so that doesn't work, it fails as trying to reference a deleted function.但似乎
std::transform
尝试复制的元素a
在某一点,这样就不会工作,它不能作为尝试引用已删除的功能。
Of course, I could just do it manually with a for loop, but I was wondering if there was a more elegant way of doing it.当然,我可以用 for 循环手动完成,但我想知道是否有更优雅的方法来做到这一点。
change the lambda to take a const &更改 lambda 以采用 const &
[](std::unique_ptr<A> const &element)-> A { return *element; });
to avoid copies due to resizing reserve correct size before transforming.避免因调整大小而产生的副本在转换前保留正确的大小。
std::vector<A> aDirect;
aDirect.reserve(a.size());
std::transform(a.begin(), a.end(),
std::back_inserter(aDirect),
[](std::unique_ptr<A> element) {
return *element;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.