Possible Duplicate:
Are std::vector elements guaranteed to be contiguous?
does std::vector always contain the data in sequential memory addresses as array[number]?
Possible Duplicate:
Are std::vector elements guaranteed to be contiguous?
does std::vector always contain the data in sequential memory addresses as array[number]?
Yes. Given:
std::vector<int> arr;
you can be sure that
&arr[0]
will give you a pointer to a contiguous array of ints that can (for instance) be passed legacy APIs.
For all types except bool, the standard requires the elements are contiguous in memory:
23.2.4/1 ... 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()
Do keep in mind that std::vector<bool>
has special requirements and is not the same as an array of bool.
Yes, the vector use sequential memory for all the elements stored. That means random access is almost as fast as normal array's index.
But vector allocate its memory in heap instead of stack. So it could be less less efficient in some cases.
When you use the standard allocator, you can be sure that the allocated memory is continuous when using std::vector. In other words, foo[n+1] is the next element in the sequence after foo[n]. But std::vector is not an array, just like
int* blah = new int[100];
is not an array. But
int blah[100];
made on the stack is an array. Pointers to allocated memory and arrays just happen to share semantics. They are not equal per the standard, so don't confuse the two.