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

Are std::vector Elements Guaranteed to Be Contiguous?

Patricia Arquette
Release: 2024-12-19 12:48:10
Original
794 people have browsed it

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template