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

Are std::vector Elements Guaranteed to Be Contiguous in Memory?

DDD
Release: 2024-12-26 05:35:38
Original
777 people have browsed it

Are std::vector Elements Guaranteed to Be Contiguous in Memory?

Can I Treat std::vector Elements as Contiguous Arrays?

The question arises whether the elements within a std::vector are guaranteed to occupy contiguous memory addresses, allowing us to treat its pointer to the first element as a C-array.

Historical Context:

In the C 98 standard, this guarantee was absent. Nevertheless, the standard's requirements for std::vector made it unlikely that elements would be non-contiguous.

Current Standard:

However, this matter was clarified in the C 0x (later renamed to C 11) standard. According to the TR that amended the C 98 standard: "The elements of a vector are stored contiguously." This means that for a vector of type other than bool, the following holds true:

&v[n] == &v[0] + n
Copy after login

where:

  • v is the vector
  • n is an index between 0 and v.size() - 1

Example:

As a result, the following code is now valid and will function as expected:

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 Are std::vector Elements Guaranteed to Be Contiguous in Memory?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template