Say I have a function:
void someFunc(int *x,int count);
which is out of my control, so I can't write it to accept iterators.
Is it safe to call it like so (regardless of the specific STL implementation):
vector<int> v;
/* ... */
someFunc(&v[0],v.size());
Obviously, one counter example is vector<bool>
. How about any other type? (assuming I haven't specialized vector
in any way).
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.
Vector occupies more memory. Array is memory efficient data structure. Vector takes more time in accessing elements.
Yes, that's fine.
From section 23.2.4, point 1 of the standard:
[...] The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().
So yes, it is safe.
Note: If v
is empty v[0]
is undefined behavior so you should only do this if v
is not empty.
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