Home > Backend Development > C++ > Is std::vector Element Memory Contiguous in C ?

Is std::vector Element Memory Contiguous in C ?

Patricia Arquette
Release: 2024-12-20 18:56:10
Original
290 people have browsed it

Is std::vector Element Memory Contiguous in C  ?

Memory Contiguity of std::Vector Elements

Concerned developers often raise the question of whether elements within a std::vector are guaranteed to be contiguous. This property determines whether it's permissible to treat the pointer to the first element as a C-style array.

Standard Provisions

Initially, the C 98 standard neglected to specify this aspect. However, subsequent technical reports (TR) rectified this oversight, and the forthcoming C 0x standard will incorporate it as an explicit requirement.

TR Specifications

N2798, a draft of C 0x, postulates:

"A vector is a sequence container that supports random access iterators ... The 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()."

Example

Based on this specification, consider the following code snippet:

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 C standard guarantees that this code will function as intended by allowing direct memory access to the vector's elements.

The above is the detailed content of Is std::vector Element Memory Contiguous in C ?. 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