Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to pass a vector as an array?

Tags:

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).

like image 787
uj2 Avatar asked Jun 22 '10 13:06

uj2


People also ask

Why would you use an array instead of a vector?

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.

Is vector more efficient than array?

Vector occupies more memory. Array is memory efficient data structure. Vector takes more time in accessing elements.

Can we treat vector as an array in C++?

Yes, that's fine.


1 Answers

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.

like image 102
mtvec Avatar answered Oct 24 '22 18:10

mtvec