Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transforming a vector<std::unique_ptr<A>> to vector<A>

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.

like image 859
Karlovsky120 Avatar asked Aug 01 '26 13:08

Karlovsky120


1 Answers

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;
               });
like image 79
Tobias Avatar answered Aug 03 '26 05:08

Tobias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!