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 thatif
block. I don't know the answer to your question, though, so I'm just leaving a comment. :) – Neustriavalues
, specifically that change its size (e.g.,push_back()
), may prompt a reallocation of the underlying vector that invalidates the pointer copied intoarray
. It's the same principle behind using a vector::iterator instead of a pointer into the vector. :) – Neustria