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];
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?
Thanks!
An alternative method uses a pointer to access the vector. w = new std::vector<int>(); The new operator creates a new, empty vector of ints and returns a pointer to that vector. We assign that pointer to the pointer variable w , and use w for the remainder of the code to access the vector we created with new .
vector data() function in C++ STL Return value: The function returns a pointer to the first element in the array which is used internally by the vector.
When we pass an array to a function, a pointer is actually passed. However, to pass a vector there are two ways to do so: Pass By value. Pass By Reference.
Conclusion. A vector of pointers is similar to a vector of objects. The main differences are as follows: The values of the vector of pointers, have to be addresses of objects declared from or instantiated from the class.
10000 int
s will not be copied. Dereferencing is very cheap.
To make it clear you can rewrite
int a = (*vecPtr)[i];
as
vector<int>& vecRef = *vecPtr; // vector is not copied here int a = vecRef[i];
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.
No, nothing will be copied; dereferencing just tells C++ that you want to invoke operator[] on the vector, not on your pointer, vecPtr
. If you didn't dereference, C++ would try to look for an operator[] defined on the std::vector<int>*
type.
This can get really confusing, since operator[]
is defined for all pointer types, but it amounts to offsetting the pointer as though it pointed to an array of vector<int>
. If you'd really only allocated a single vector there, then for any index other than 0
, the expression evaluates to a reference to garbage, so you'll get either a segfault or something you did not expect.
In general, accessing vectors through a pointer is a pain, and the (*vecPtr)[index]
syntax is awkward (but better than vecPtr->operator[](index)
). Instead, you can use:
vecPtr->at(index)
This actually checks ranges, unlike operator[]
, so if you don't want to pay the price for checking if index is in bounds, you're stuck with (*vecPtr)[]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With