开发者

Get vector of pointers from vector in C++

I开发者_如何学JAVAs 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.


As @Benoit suggested, it is a bad idea to store these pointers. But if you really want to do it, you can use std::transform like this:

template<class T>
struct Address
{
    T* operator()(T& t) const
    {
        return &t;
    }
};


template<class T>
vector<T*> fn(vector<T>&  v)
{
  vector<T*> r;
  transform(v.begin(), v.end(), back_inserter(r), Address<T>());
  return r;
}


int main( void )
{
    vector<int> a;
    a.push_back(0);
    fn(a);
}


You could do something along the lines of:

template <typename T>
T* mk_ptr(T& t) {
  return &t;
}

template <typename T>
std::vector<T*> fn(std::vector<T>& v) {
  std::vector<T*> r;
  std::transform(v.begin(), v.end(), std::back_inserter(r), mk_ptr);
  return r;
}

But one has to wonder about the motivation of this... There are iterators for a reason. Noone guarantees that the pointers will remain valid.


First of all you have to find a correct way. Your code (edit: the original code where v is passed by value, that is) is wrong and gives rise to undefined behavior. Depending on the application, you usually want either a pointer container or a normal container that stores smart pointers.


There's no standard library function to do this.

std::vector<T*> pv(v.size());
for (size_t i=0; i<v.size(); ++i)
    pv[i] = &v[i];

is probably the shortest expression of this loop if you don't use C++0x lambdas.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜