I would like to be able to convert between std::vector and its underlying C array int* without explicitly copying the data.
Does std::vector provide access to the underlying C array? I am looking for something like this
vector<int> v (4,100) int* pv = v.c_array();
EDIT:
Also, is it possible to do the converse, i.e. how would I initialize an std::vector
from a C array without copying?
int pv[4] = { 4, 4, 4, 4}; vector<int> v (pv);
To convert an array to vector, you can use the constructor of Vector, or use a looping statement to add each element of array to vector using push_back() function.
The syntax for assigning values from an array or list: vectorname. assign(arr, arr + size) Parameters: arr - the array which is to be assigned to a vector size - number of elements from the beginning which has to be assigned.
There is a myth that for run-time speed, one should use arrays. A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program.
Vector is better for frequent insertion and deletion, whereas Arrays are much better suited for frequent access of elements scenario. Vector occupies much more memory in exchange for managing storage and growing dynamically, whereas Arrays are a memory-efficient data structure.
You can get a pointer to the first element as follows:
int* pv = &v[0];
This pointer is only valid as long as the vector is not reallocated. Reallocation happens automatically if you insert more elements than will fit in the vector's remaining capacity (that is, if v.size() + NumberOfNewElements > v.capacity()
. You can use v.reserve(NewCapacity)
to ensure the vector has a capacity of at least NewCapacity
.
Also remember that when the vector gets destroyed, the underlying array gets deleted as well.
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