Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert vector of pointer to vector of objects

Tags:

c++

c++11

vector

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.

like image 364
Humam Helfawi Avatar asked Feb 16 '16 09:02

Humam Helfawi


2 Answers

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;});
like image 118
Jarod42 Avatar answered Oct 05 '22 22:10

Jarod42


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.

like image 44
Rob L Avatar answered Oct 06 '22 00:10

Rob L