访问元素的引用向量指针 [英] Dereference vector pointer to access element

查看:88
本文介绍了访问元素的引用向量指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在C ++中有一个向量的指针:

If i have in C++ a pointer to a vector:

vector<int>* vecPtr;

我想访问一个向量元素,然后我可以通过dereferncing vector:

And i'd like to access an element of the vector, then i can do this by dereferncing the vector:

int a = (*vecPtr)[i];

但是这个解引用实际上是否会在栈上创建一个我的向量的副本?让我们说向量存储10000个int,将通过解除引用vecPtr 10000 int被复制?

but will this dereferencing actually create a copy of my vector on the stack? let's say the vector stores 10000 ints, will by dereferencing the vecPtr 10000 ints be copied?

谢谢!

推荐答案

10000 int 不会被复制。取消引用非常便宜。

10000 ints will not be copied. Dereferencing is very cheap.

清楚你可以重写

int a = (*vecPtr)[i];

vector<int>& vecRef = *vecPtr; // vector is not copied here
int a = vecRef[i];

此外,如果你害怕整个数据存储在 / code>将位于栈上,并使用向量< int> * 而不是向量< int> 避免这样:这不是这样的。
实际上,堆栈上只使用固定数量的内存(大约16-20字节,取决于实现),与存储在向量中的元素数量无关。
向量本身分配内存并在堆上存储元素。

In addition, if you are afraid that the whole data stored in vector will be located on the stack and you use vector<int>* instead of vector<int> to avoid this: this is not the case. Actually only a fixed amount of memory is used on the stack (about 16-20 bytes depending on the implementation), independently of the number of elements stored in the vector. The vector itself allocates memory and stores elements on the heap.

这篇关于访问元素的引用向量指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆