Contiguity of std::vector Elements
The question arises whether std::vector elements are guaranteed to be contiguous, enabling the use of the vector's first element pointer as a C-array. Despite the lack of an explicit guarantee in the C 98 standard, it was difficult to meet the std::vector requirements without contiguity.
The C 0x standard rectified this omission, as indicated in n2798:
"A vector is a sequence container that supports ... 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()."
This confirms that std::vector elements are indeed stored contiguously, permitting the use of a pointer to the first element as a C-array:
std::vectorvalues; // ... 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' } } The above is the detailed content of Are std::vector Elements Guaranteed to Be Contiguous?. For more information, please follow other related articles on the PHP Chinese website!