Home >Backend Development >C++ >Are std::vector Elements Guaranteed to Be Contiguous?

Are std::vector Elements Guaranteed to Be Contiguous?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-19 12:48:10866browse

Are std::vector Elements Guaranteed to Be Contiguous?

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::vector 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'
    }
}

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn