My question is simple: are std::vector
elements guaranteed to be contiguous? In other words, can I use the pointer to the first element of a std::vector
as a C-array?
If my memory serves me well, the C++ standard did not make such guarantee. However, the std::vector
requirements were such that it was virtually impossible to meet them if the elements were not contiguous.
Can somebody clarify this?
Example:
std::vector<int> values;
// ... fill up values
if( !values.empty() )
{
int *array = &values[0];
for( int i = 0; i < values.size(); ++i )
{
int v = array[i];
// do something with 'v'
}
}
values
inside that if
block. I don't know the answer to your question, though, so I'm just leaving a comment. :)
values
, specifically that change its size (e.g., push_back()
), may prompt a reallocation of the underlying vector that invalidates the pointer copied into array
. It's the same principle behind using a vector::iterator instead of a pointer into the vector. :)
This was missed from C++98 standard proper but later added as part of a TR. The forthcoming C++0x standard will of course contain this as a requirement.
From n2798 (draft of C++0x):
23.2.6 Class template vector [vector] 1 A vector is a sequence container that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time. Storage management is handled automatically, though hints can be given to improve efficiency. 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().
As other answers have pointed out, the contents of a vector is guaranteed to be continuous (excepting bool's weirdness).
The comment that I wanted to add, is that if you do an insertion or a deletion on the vector, which could cause the vector to reallocate it's memory, then you will cause all of your saved pointers and iterators to be invalidated.
vector.push_back(3)
is an insertion, so it invalidates iterators. 2. I wouldn't expect swap(vector[3], vector[4])
to invalidate iterators, since no new memory is allocated, but I have no reference to back that up. 3. swap(vector_1, vector_2)
is interesting. I probably wouldn't trust the iterators after this, but I don't know for sure if they continue to be valid.
The standard does in fact guarantee that a vector
is continuous in memory and that &a[0]
can be passed to a C
function that expects an array.
The exception to this rule is vector<bool>
which only uses one bit per bool
thus although it does have continuous memory it can't be used as a bool*
(this is widely considered to be a false optimization and a mistake).
BTW, why don't you use iterators? That's what they're for.
As other's have already said, vector
internally uses a contiguous array of objects. Pointers into that array should be treated as invalid whenever any non-const member function is called IIRC.
However, there is an exception!!
vector<bool>
has a specialised implementation designed to save space, so that each bool only uses one bit. The underlying array is not a contiguous array of bool and array arithmetic on vector<bool>
doesn't work like vector<T>
would.
(I suppose it's also possible that this may be true of any specialisation of vector, since we can always implement a new one. However, std::vector<bool>
is the only, err, standard specialisation upon which simple pointer arithmetic won't work.)
std::vector
, and all other vectors are required to use contiguous storage. Therefore, std::vector<bool>
is (fortunately) the only standard vector that's weird. (I'm strongly of the opinion that this specialization should be deprecated and replaced by e.g. a std::dynamic_bitset
with much the same functionality. It's not a bad data structure, it's just not a vector.)
I found this thread because I have a use case where vectors using contiguous memory is an advantage.
I am learning how to use vertex buffer objects in OpenGL. I created a wrapper class to contain the buffer logic, so all I need to do is pass an array of floats and a few config values to create the buffer. I want to be able to generate a buffer from a function based on user input, so the length is not known at compile time. Doing something like this would be the easiest solution:
void generate(std::vector<float> v)
{
float f = generate_next_float();
v.push_back(f);
}
Now I can pass the vector's floats as an array to OpenGL's buffer-related functions. This also removes the need for sizeof to determine the length of the array.
This is far better than allocating a huge array to store the floats and hoping I made it big enough, or making my own dynamic array with contiguous storage.
v
rather than v
itself? because passing v
alone will cause a copy to be made inside the function, which will cease to exist after the function ends. Thus you are pushing something onto the vector only to delete the vector when the function ends.
Vector containers are implemented as dynamic arrays; Just as regular arrays, vector containers have their elements stored in contiguous storage locations, which means that their elements can be accessed not only using iterators but also using offsets on regular pointers to elements.
Yes, the elements of a std::vector are guaranteed to be contiguous.
Success story sharing
std::vector
that are contiguous. Eg.: instd::vector<std::vector<int>> v
the elementsv[0]
,v[1]
, ... are stored subsequently in memory, but the elementv[0].back()
andv[1].front()
are not guaranteed to be.