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 ints 不会被复制.取消引用非常便宜.
10000 ints 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.
这篇关于取消引用指向访问元素的向量指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:取消引用指向访问元素的向量指针
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
