Humam Helfawi
Humam Helfawi

Reputation: 20324

Convert vector of pointer to vector of objects

I have this vector:

std::vector<T*> foo;

I have a function with the following signature (I can not alter it):

void bar(std::vector<T> const&);

How Can I pass foo to that function with minimum changes?

My current approach is:

std::vector<T> another_bar(bar.size());
std::transform(std::begin(bar),std::end(bar),std::begin(another_bar),[](T* item){return *T;});

I think there is a lot of unnecessary copying is happening here.

EDIT:

T is not a templated parameter. It is a specified type.

Upvotes: 6

Views: 2232

Answers (3)

Jarod42
Jarod42

Reputation: 218278

Whereas you need to to some copies, you may avoid to construct default value and then create copy by direct copy construct:

std::vector<T> another_bar;
another_bar.reserve(bar.size());
std::transform(std::begin(bar), std::end(bar),
               std::back_inserter(another_bar),[](T* item){return *item;});

Upvotes: 6

Zulan
Zulan

Reputation: 22670

Since T is a specific given type, there is no way to avoid the copy without modifying either T or bar.

If you can make T generic, you could create sort of a "PIMPL-wrapper": An object that internally contains a pointer to a real T and implements the same interface of T by calling the respective functions internally.

In other words, your transformation code looks good.

Upvotes: 2

Rob L
Rob L

Reputation: 2530

Your approach is as correct as possible. You have to do a lot of copying. Another problem is that it will also "slice" if you have any classes derived from T. Sometimes you have two dissimilar programs and it is unavoidable, but more likely you should reevaluate the design of either the caller or the function.

Upvotes: 3

Related Questions