Using std::vector as a C array

suggest change

There are several ways to use a std::vector as a C array (for example, for compatibility with C libraries). This is possible because the elements in a vector are stored contiguously.

std::vector<int> v{ 1, 2, 3 };
int* p = v.data();

In contrast to solutions based on previous C++ standards (see below), the member function .data() may also be applied to empty vectors, because it doesn’t cause undefined behavior in this case.

Before C++11, you would take the address of the vector’s first element to get an equivalent pointer, if the vector isn’t empty, these both methods are interchangeable:

int* p = &v[0];      // combine subscript operator and 0 literal

int* p = &v.front(); // explicitly reference the first element

Note: If the vector is empty, v[0] and v.front() are undefined and cannot be used.

When storing the base address of the vector’s data, note that many operations (such as push_back, resize, etc.) can change the data memory location of the vector, thus invalidating previous data pointers. For example:

std::vector<int> v;
int* p = v.data();
v.resize(42);      // internal memory location changed; value of p is now invalid

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


std::vector:
* Using std::vector as a C array

Table Of Contents
8 Arrays
11 Loops
23 std::vector
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype