Home > Backend Development > C++ > Is `std::vector`'s Element Storage Guaranteed to Be Contiguous in C ?

Is `std::vector`'s Element Storage Guaranteed to Be Contiguous in C ?

Patricia Arquette
Release: 2024-12-30 12:18:09
Original
801 people have browsed it

Is `std::vector`'s Element Storage Guaranteed to Be Contiguous in C  ?

Are std::vector Elements Guaranteed to Be Contiguous?

While the C 98 standard did not explicitly guarantee contiguous elements within a std::vector, the requirements for std::vector made it highly unlikely that the elements would not be contiguous. However, this was later clarified as a requirement in the n2798 draft of the C 0x standard.

The upcoming C 0x standard includes the following requirement:

A vector is a sequence container that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time. Storage management is handled automatically, though hints can be given to improve efficiency. 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().
Copy after login

This means that you can safely use the pointer to the first element of a std::vector as a C-array, as in the following example:

std::vector<int> 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'
    }
}
Copy after login

The above is the detailed content of Is `std::vector`'s Element Storage Guaranteed to Be 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