Is there an easy way of creating a vector of pointers to the elements of a vector?
i.e. easier than the below
std::vector<T*> fn(std::vector<T> &v)
{
std::vector<T*> r;
for (int i = 0; i < v.size(); i++)
{
r.push_back(&v[i]);
}
return r;
}
EDIT: Incoming vector by reference
I see no reason why you would need to do this. If you grow v your pointers may become invalid; and r[i] are just aliases for &v[i].
If you really need to pass pointers (we still did not understand why) you can just pass &v[0] and the size of the vector. Given that all implementation of std::vector must guarantee that elements in a vector are stored contiguously in memory, you can deduce all addresses from the address of the first element and the size of the vector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With