Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get vector of pointers from vector in C++

Tags:

c++

stl

vector

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

like image 758
Sam Avatar asked Mar 22 '26 20:03

Sam


1 Answers

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.

like image 121
Benoit Avatar answered Mar 25 '26 09:03

Benoit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!