Dereference vector pointer to access element(取消引用指向访问元素的向量指针)
问题描述
如果我在 C++ 中有一个指向向量的指针:
If i have in C++ a pointer to a vector:
vector<int>* vecPtr;
我想访问向量的一个元素,然后我可以通过取消引用向量来做到这一点:
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 个整数,是否会通过取消引用 vecPtr 来复制 10000 个整数?
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
s 不会被复制.取消引用非常便宜.
10000 int
s will not be copied. Dereferencing is very cheap.
为清楚起见,您可以重写
To make it clear you can rewrite
int a = (*vecPtr)[i];
作为
vector<int>& vecRef = *vecPtr; // vector is not copied here
int a = vecRef[i];
此外,如果您担心存储在 vector
中的整个数据将位于堆栈中,则使用 vector
而不是 vector
以避免这种情况:情况并非如此.实际上,堆栈上只使用了固定数量的内存(大约 16-20 字节,具体取决于实现),与 vector
中存储的元素数量无关.vector
本身分配内存并将元素存储在堆上.
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.
这篇关于取消引用指向访问元素的向量指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:取消引用指向访问元素的向量指针


- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 从python回调到c++的选项 2022-11-16
- C++ 协变模板 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 静态初始化顺序失败 2022-01-01