1

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?

Mat
  • 11,263
  • 10
  • 45
  • 48

2 Answers2

4

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.

  • 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. – Bill Lynch Apr 05 '10 at 14:00
0

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
  • 5,312
  • 20
  • 25
  • Wasn't my downvote, but I did add the last paragraph in my answer in response---you can access it directly. –  Nov 20 '09 at 02:37
  • 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 Nov 20 '09 at 02:47