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'
}
}
Best Answer
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):