Reputation: 6352
There is a vector of std::unique_ptr<A>
. I need to pass that data to a function that expects a vector of A
.
I tried using std::transform
, like this:
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.
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.
Upvotes: 2
Views: 205
Reputation: 845
change the lambda to take a 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;
});
Upvotes: 8