Minimal conversion of vector to pointer vector

Is there any shortcut to convert from std::vector<T>to std::vector<T*>or to 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 one line.

To provide some context: I have one set of functions that perform their calculations on std::vector<Polygon>, and some of them require std::vector<Polygon*>. Therefore, I need to convert back and forth a couple of times, because the interface of these functions should not change.

+5
source share
3 answers

Although what you describe sounds weird (no context) using std::transform, you can actually copy / convert in a single line of code

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

, target ( std::vector::resize, .),

template<typename T> T* getPointer(T& t) { return &t; }
+10

++ 0x, (++ 0x, lambdas):

template <typename T>
std::vector<T*> convertFrom(std::vector<T>& source)
{
    std::vector<T*> target(source.size());
    std::transform(source.begin(), source.end(), target.begin(), [](T& t) { return &t; });
    return target;
}

. , , . .

+5

- .

, , :

boost::transform_iterator:

template<typename T> T* getPointer(T& t) { return &t; }
boost::transform_iterator<T* (*)(T&), std::vector<T>::iterator> begin(source.begin(), getPointer), end(source.end(), getPointer);
std::vector<T*> target(begin, end);

source target ( ), boost::indirect_iterator:

boost::indirect_iterator<std::vector<T*>::iterator> begin(target.begin()), end(target.end());
std::vector<T> source(begin, end);

, .

+1
source

All Articles