tags:

views:

189

answers:

2

If I create a std::vector with the default allocator like this:

vector<int> myVec = vector<int>();
myVec.push_back(3);
myVec.push_back(5);
myVec.push_back(8);

Does the vector then store the actual data internally into an array of int? Is it possible to get a pointer to this array and iterate directly over it using this pointer?

+3  A: 

Yes, vector is designed so you can do this, use &myVec[0] to get an int*. You can also use vector's iterator type, which behaves similarly. (Pointers are valid random-access iterators.) That you're using the default allocator, or any other allocator, doesn't change any of this, it's a required part of vector's interface.

Vectors are guaranteed to use contiguous storage. In particular from those many results, check this one from Stroustrup himself.

Roger Pate
thanks a lot :)
Mat
The only caveat to this is that if you add or remove elements, you could cause a reallocation which could move the vector in memory.
sharth
A: 

For gcc 4.4 this operator is defined as:

operator[](size_type __n)
{ return *(this->_M_impl._M_start + __n); }

So, we can say that items are stored as a regular array, and you can access them directly

Edited

Elalfer
Wasn't my downvote, but I did add the last paragraph in my answer in response---you can access it directly.
Roger Pate
yeah, you can access it `_M_impl._M_start` should point to it.http://stackoverflow.com/questions/849168/are-stdvector-elements-guaranteed-to-be-continguous here is another useful answer on the same question
Elalfer