Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest conversion from vector to vector of pointer

Tags:

c++

stl

Is there any shortcut to convert from std::vector<T> to std::vector<T*> or std::vector<T&>?

Essentially I want to replace:

std::vector<T> source;
std::vector<T*> target;
for(auto it = source.begin(); it != source.end(); it++)
{
  target.push_back(&(*it));
}

with a single line.

To provide some context: I have one set of functions which do their computation on a std::vector<Polygon> and some which require std::vector<Polygon*>. So I need to convert back and forth a couple of times, because the interface of these functions is not supposed to change.

like image 815
Christopher Oezbek Avatar asked Jul 29 '11 07:07

Christopher Oezbek


1 Answers

Although what you describe sounds strange (without context), using std::transform you could do the actual copying/transformation in one line of code :

transform(source.begin(), source.end(), target.begin(), getPointer);

given that target has sufficient room for all data (can be achieved with std::vector::resize eg.), and given this unary operator :

template<typename T> T* getPointer(T& t) { return &t; }
like image 168
Sander De Dycker Avatar answered Sep 23 '22 05:09

Sander De Dycker