c_plus_plus_container_vector

C++ Container Vector

https://en.cppreference.com/w/cpp/container/vector

@1@

is a sequence container that encapsulates dynamic size arrays. @2@

is an alias template that uses a polymorphic allocator.

The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements. This means that a pointer to an element of a vector may be passed to any function that expects a pointer to an element of an array.

The storage of the vector is handled automatically, being expanded and contracted as needed. Vectors usually occupy more space than static arrays, because more memory is allocated to handle future growth. This way a vector does not need to reallocate each time an element is inserted, but only when the additional memory is exhausted. The total amount of allocated memory can be queried using

function.

.}}

Reallocations are usually costly operations in terms of performance. The

function can be used to eliminate reallocations if the number of elements is known beforehand.

The complexity (efficiency) of common operations on vectors is as follows:

  • Random access - constant
  • Insertion or removal of elements at the end - amortized constant
  • Insertion or removal of elements - linear in the distance to the end of the vector

(for

other than

) meets the requirements of

,

,

}} and

.

are

: it is possible to create and use

objects in the evaluation of a constant expression.

However,

objects generally cannot be

, because any dynamically allocated storage must be released in the same evaluation of constant expression. }}

Template parameters

Specializations

The standard library provides a specialization of

for the type

, which may be optimized for space efficiency.

Iterator invalidation

Operations Invalidated
All read only operations Never

,

,

,

Always

,

If the vector changed capacity, all of them. If not, none.

Erased elements and all elements after them (including

)

,

If the vector changed capacity, all of them. If not, only end().

,

If the vector changed capacity, all of them. If not, only those at or after the insertion point (including end()).

If the vector changed capacity, all of them. If not, only end() and any elements erased.

The element erased and

.

Member types

Member functions

| vector}}

Non-member functions

{{rl|deduction guides|Deduction guides}}{{mark since c++17}}

Example

Defect reports

was not required|after=required}}

resulted in UB|after=

function provided}}

c_plus_plus_container_vector.txt · Last modified: 2024/04/28 03:32 (external edit)