[英]Get vector of pointers from vector in C++
Is there an easy way of creating a vector of pointers to the elements of a vector? 有没有一种简单的方法来创建一个指向矢量元素的指针向量?
ie 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; 如果你长大v
你的指针可能会变得无效; and r[i]
are just aliases for &v[i]
. 并且r[i]
只是&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. 如果你真的需要传递指针(我们仍然不明白为什么)你可以传递&v[0]
和向量的大小。 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. 鉴于std::vector
所有实现必须保证std::vector
中的元素连续存储在内存中,您可以从第一个元素的地址和向量的大小推导出所有地址。
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. 如果你不使用C ++ 0x lambdas,它可能是这个循环的最短表达式。
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. 没有人保证指针仍然有效。
As @Benoit suggested, it is a bad idea to store these pointers. 正如@Benoit建议的那样,存储这些指针是个坏主意。 But if you really want to do it, you can use std::transform
like this: 但是如果你真的想这样做,你可以像这样使用std::transform
:
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);
}
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. 您的代码( 编辑: v
通过值传递的原始代码,即)是错误的,并导致未定义的行为。 Depending on the application, you usually want either a pointer container or a normal container that stores smart pointers . 根据应用程序的不同,您通常需要指针容器或存储智能指针的普通容器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.