# std::vector

> C++ Atlas: `cppatlas.com/w/cpp/container/vector` | Source: https://en.cppreference.com/w/cpp/container/vector | Domain: Containers | Standards: C++11, C++17, C++20, C++23, C++26

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.

## Executive Mental Model (Study Companion)

**Core Intuition:** T&& is a forwarding reference ONLY when T is a deduced template parameter of that exact function—not std::vector<T>&&.

- **Standard Era:** C++11 → C++20 → C++23
- **Primary ISO Clauses:** [dcl.ref], [temp.deduct.call], [class.copy.ctor], [utility.syn]
- **CppCon Talk Angle:** Show the exact 24-byte stack footprint of std::vector: copying duplicates the heap allocation, moving copies 3 pointers and nulls the source.
- **Common Audience Trap:** Forgetting noexcept on a custom move constructor, forcing std::vector::push_back to fall back to O(N) deep copies for exception safety.
- **Stage Takeaway:** Universal reference collapsing has one simple rule: '&' is infectious (& + anything = &). Only && + && yields &&.

## Memory Map Walkthrough: Stack/Heap Move Layout & Reference Collapsing Lab

Moving an owning container like std::vector does not move heap elements; it copies the 24-byte stack control block (begin, end, capacity pointers) into the destination and resets the source pointers to null in O(1) time. However, to preserve the strong exception guarantee during std::vector reallocation, std::vector calls std::move_if_noexcept—meaning if your user-defined move constructor is missing noexcept, vector silently copies every element instead of moving! Meanwhile, forwarding references (T&& or auto&&) leverage reference collapsing ([dcl.ref]): when an lvalue Widget passes to template<class T> void f(T&&), T deduces to Widget&, and Widget& && collapses to Widget&, letting std::forward<T> preserve the caller's exact value category.

### The noexcept move constructor cliff ([utility.move.if.noexcept] & [vector.capacity])

std::vector::push_back promises the strong exception guarantee: if reallocation fails halfway through migrating elements from the old buffer to the new buffer, the vector remains unchanged.

If moving element #50 out of 100 throws an exception, the old buffer already has 49 moved-from husks that cannot be rolled back. Therefore std::vector uses std::move_if_noexcept—it moves ONLY when the move constructor is noexcept (or when no copy constructor exists).

*noexcept unlocks fast vector growth:*
```cpp
struct Buffer {
    int* data = nullptr;
    Buffer(Buffer&& other) noexcept   // <-- omit noexcept and vector COPIES!
        : data(std::exchange(other.data, nullptr)) {}
    Buffer(const Buffer& other);
};
```

**Key takeaway:** Always mark user-defined move constructors and move assignment operators noexcept whenever they cannot throw.

### Forwarding reference vs. rvalue reference & collapsing ([temp.deduct.call] & [dcl.ref])

The syntax T&& means 'rvalue reference' everywhere EXCEPT when T is a deduced type parameter of that function template (or auto&&). Any cv-qualifier (const T&&) or wrapper (std::vector<T>&&) disables the forwarding-reference rule and becomes a plain rvalue reference.

When T&& IS a forwarding reference and receives an lvalue of type X, template deduction makes an intentional exception: T deduces to X&. Then reference collapsing fires: X& + && collapses to X&. Passing an rvalue deduces T = X, leaving X&&.

*Reference collapsing matrix:*
```cpp
template <class T>
void relay(T&& arg) {
    sink(std::forward<T>(arg));
}

Widget w;
relay(w);            // T = Widget&,  arg = Widget&  (lvalue)
relay(Widget{});     // T = Widget,   arg = Widget&& (xvalue after forward)
relay(std::move(w)); // T = Widget,   arg = Widget&&
```

**Key takeaway:** Any single & in a reference collapse (& &, & &&, && &) yields &; only && + && stays &&.

## Official Specification Summary (cppreference)

```cpp
// Defined in header <vector>

template<
    class T,
    class Allocator = std::allocator<T>
> class vector; // (1)

namespace pmr {
    template< class T >
    using vector = std::vector<T, std::pmr::polymorphic_allocator<T>>;
} // (2) (since C++17)
```

1) `std::vector` is a sequence container that encapsulates dynamic size arrays.

2) `std::pmr::vector` 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 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 `capacity()` function. Extra memory can be returned to the system via a call to `shrink_to_fit()`[1].

Reallocations are usually costly operations in terms of performance. The `reserve()` 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 𝓞(1).
- Insertion or removal of elements at the end - amortized constant 𝓞(1).
- Insertion or removal of elements - linear in the distance to the end of the vector 𝓞(n).

`std::vector` (for `T` other than `bool`) meets the requirements of *Container*, *AllocatorAwareContainer* (since C++11), *SequenceContainer*, *ContiguousContainer* (since C++17) and *ReversibleContainer*.

(since C++20):

Member functions of `std::vector` are `constexpr`: it is possible to create and use `std::vector` objects in the evaluation of a constant expression.

However, `std::vector` objects generally cannot be `constexpr`, because any dynamically allocated storage must be released in the same evaluation of constant expression.

1. ↑ In libstdc++, `shrink_to_fit()` is not available in C++98 mode.

### Template parameters

- `T` - The type of the elements.

  `T` must meet the requirements of *CopyAssignable* and *CopyConstructible*. (until C++11)

  The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type is a complete type and meets the requirements of *Erasable*, but many member functions impose stricter requirements. (since C++11) (until C++17)

  (since C++17):

  The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type meets the requirements of *Erasable*, but many member functions impose stricter requirements. This container (but not its members) can be instantiated with an incomplete element type if the allocator satisfies the allocator completeness requirements.

  | Feature-test macro | Value | Std | Feature |
  | --- | --- | --- | --- |
  | `__cpp_lib_incomplete_container_elements` | `201505L` | (C++17) | Minimal incomplete type support |
- `Allocator` - An allocator that is used to acquire/release memory and to construct/destroy the elements in that memory. The type must meet the requirements of *Allocator*. The behavior is undefined (until C++20) The program is ill-formed (since C++20) if `Allocator::value_type` is not the same as `T`.

### Specializations

The standard library provides a specialization of `std::vector` for the type `bool`, which may be optimized for space efficiency.

- `vector<bool>`: space-efficient dynamic bitset (class template specialization)

### Iterator invalidation

| Operations | Invalidated |
| --- | --- |
| All read only operations | Never. |
| `swap`, `std::swap` | `end()` |
| `clear`, `operator=`, `assign` | Always. |
| `reserve`, `shrink_to_fit` | If the vector changed capacity, all of them. If not, none. |
| `erase` | Erased elements and all elements after them (including `end()`). |
| `push_back`, `emplace_back` | If the vector changed capacity, all of them. If not, only `end()`. |
| `insert`, `emplace` | If the vector changed capacity, all of them. If not, only those at or after the insertion point (including `end()`). |
| `resize` | If the vector changed capacity, all of them. If not, only `end()` and any elements erased. |
| `pop_back` | The element erased and `end()`. |

### Member types

**Member type — Definition**

- `value_type`: `T`
- `allocator_type`: `Allocator`
- `size_type`: Unsigned integer type (usually `std::size_t`)
- `difference_type`: Signed integer type (usually `std::ptrdiff_t`)
- `reference`: `value_type&`
- `const_reference`: `const value_type&`
- `pointer`: `Allocator::pointer` (until C++11) `std::allocator_traits<Allocator>::pointer` (since C++11)
- `const_pointer`: `Allocator::const_pointer` (until C++11) `std::allocator_traits<Allocator>::const_pointer` (since C++11)
- `iterator`: *LegacyRandomAccessIterator* and *LegacyContiguousIterator* to `value_type` (until C++20) *LegacyRandomAccessIterator*, `contiguous_iterator`, and *ConstexprIterator* to `value_type` (since C++20)
- `const_iterator`: *LegacyRandomAccessIterator* and *LegacyContiguousIterator* to `const value_type` (until C++20) *LegacyRandomAccessIterator*, `contiguous_iterator`, and *ConstexprIterator* to `const value_type` (since C++20)
- `reverse_iterator`: `std::reverse_iterator<iterator>`
- `const_reverse_iterator`: `std::reverse_iterator<const_iterator>`

### Member functions

- (constructor): constructs the `vector` (public member function)
- (destructor): destructs the `vector` (public member function)
- `operator=`: assigns values to the container (public member function)
- `assign`: assigns values to the container (public member function)
- `assign_range` (C++23): assigns a range of values to the container (public member function)
- `get_allocator`: returns the associated allocator (public member function)

**Element access**

- `at`: access specified element with bounds checking (public member function)
- `operator[]`: access specified element (public member function)
- `front`: access the first element (public member function)
- `back`: access the last element (public member function)
- `data`: direct access to the underlying contiguous storage (public member function)

**Iterators**

- `begin`, `cbegin` (C++11): returns an iterator to the beginning (public member function)
- `end`, `cend` (C++11): returns an iterator to the end (public member function)
- `rbegin`, `crbegin` (C++11): returns a reverse iterator to the beginning (public member function)
- `rend`, `crend` (C++11): returns a reverse iterator to the end (public member function)

**Capacity**

- `empty`: checks whether the container is empty (public member function)
- `size`: returns the number of elements (public member function)
- `max_size`: returns the maximum possible number of elements (public member function)
- `reserve`: reserves storage (public member function)
- `capacity`: returns the number of elements that can be held in currently allocated storage (public member function)
- `shrink_to_fit` (DR*): reduces memory usage by freeing unused memory (public member function)

**Modifiers**

- `clear`: clears the contents (public member function)
- `insert`: inserts elements (public member function)
- `insert_range` (C++23): inserts a range of elements (public member function)
- `emplace` (C++11): constructs element in-place (public member function)
- `erase`: erases elements (public member function)
- `push_back`: adds an element to the end (public member function)
- `emplace_back` (C++11): constructs an element in-place at the end (public member function)
- `append_range` (C++23): adds a range of elements to the end (public member function)
- `pop_back`: removes the last element (public member function)
- `resize`: changes the number of elements stored (public member function)
- `swap`: swaps the contents (public member function)

### Non-member functions

- `operator==`, `operator!=` (removed in C++20), `operator<` (removed in C++20), `operator<=` (removed in C++20), `operator>` (removed in C++20), `operator>=` (removed in C++20), `operator<=>` (C++20): lexicographically compares the values of two `vector`s (function template)
- `std::swap(std::vector)`: specializes the `std::swap` algorithm (function template)
- `erase(std::vector)` (C++20), `erase_if(std::vector)`: erases all elements satisfying specific criteria (function template)

### Deduction guides (since C++17)

### Notes

| Feature-test macro | Value | Std | Feature |
| --- | --- | --- | --- |
| `__cpp_lib_containers_ranges` | `202202L` | (C++23) | Ranges construction and insertion for containers |

### Example

```cpp
#include <iostream>
#include <vector>

int main()
{
    // Create a vector containing integers
    std::vector<int> v = {8, 4, 5, 9};

    // Add two more integers to vector
    v.push_back(6);
    v.push_back(9);

    // Overwrite element at position 2
    v[2] = -1;

    // Print out the vector
    for (int n : v)
        std::cout << n << ' ';
    std::cout << '\n';
}
```

Output:

```text
8 4 -1 9 6 9
```

### Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| LWG 69 | C++98 | contiguity of the storage for elements of `vector` was not required | required |
| LWG 230 | C++98 | `T` was not required to be *CopyConstructible* (an element of type `T` might not be able to be constructed) | `T` is also required to be *CopyConstructible* |
| LWG 464 | C++98 | access to the underlying storage of an empty `vector` resulted in UB | `data` function provided |

### See also

- [`inplace_vector`](https://en.cppreference.com/w/cpp/container/inplace_vector) (C++26): dynamically-resizable, fixed capacity, inplace contiguous array (class template)
- [`array`](https://en.cppreference.com/w/cpp/container/array) (C++11): fixed-sized inplace contiguous array (class template)
- [`deque`](https://en.cppreference.com/w/cpp/container/deque): double-ended queue (class template)

## Podcast Host Debate & Socratic Standard Traps

Use the prompts and tricky ISO standard questions below to guide a Socratic audio discussion:

- Break down what std::vector actually puts on the stack versus the heap, and why moving a million-element vector costs three pointer assignments.
- Tell the story of the missing noexcept move constructor and how std::move_if_noexcept quietly saves exception safety at the cost of speed.
- Clarify why Box<T>::push(T&&) is NOT a forwarding reference even though T&& looks identical.

### Trap 1: [vector.modifiers] & [utility.move.if.noexcept] (cppcon-stage)

Widget defines BOTH a copy constructor and a non-noexcept move constructor. What does std::vector<Widget>::push_back invoke on existing elements during buffer growth?

```cpp
struct Widget {
    Widget(const Widget&);
    Widget(Widget&&); // Note: NOT marked noexcept
};
```

A. The move constructor, because std::vector always moves existing items
B. The copy constructor, via std::move_if_noexcept, to preserve the strong exception guarantee
C. Compile error: move constructors must be noexcept to live in std::vector
D. memcpy bitwise relocation

**Standard Answer (B):** The copy constructor, via std::move_if_noexcept, to preserve the strong exception guarantee

**Why:** Because Widget has a copy constructor and its move constructor might throw, std::move_if_noexcept yields const Widget& so std::vector copies elements safely into the new buffer before freeing the old buffer.

### Trap 2: [temp.deduct.call] §13.10.3.2 (standard-lawyer)

Which function parameter is actually a forwarding (universal) reference?

A. template<class T> void f(std::vector<T>&& v);
B. template<class T> void f(const T&& v);
C. template<class T> struct Box { void push(T&& v); };
D. auto&& x = expr;

**Standard Answer (D):** auto&& x = expr;

**Why:** std::vector<T>&& and const T&& are plain rvalue references. Box<T>::push(T&&) is NOT deduced at the push() call site because T was already fixed by Box<T>! Only auto&& (or a template function's own deduced T&&) is a forwarding reference.

*CppCon speaker note:* Box<T>::push(T&&) is a notorious class-template surprise (think std::vector<T>::push_back(T&&)).

### Trap 3: [dcl.ref] §9.3.4.3 (subtle)

Given using LRef = int&; and using RRef = int&&;, what type does LRef&& collapse to?

A. int&&
B. int&
C. int
D. Ill-formed: references to references are always illegal

**Standard Answer (B):** int&

**Why:** While writing int& && directly in source is illegal, forming a reference to a reference through type aliases, decltype, or template substitution collapses via [dcl.ref]: if either reference is an lvalue reference (&), the result is an lvalue reference (int&).

### Trap 4: [lib.types.movedfrom] (subtle)

After std::string b = std::move(a);, what operations are guaranteed valid on the moved-from string a?

A. a is guaranteed to be empty (a.empty() == true)
B. Only destruction and reassignment are valid; calling a.clear() is UB
C. a is in a valid but unspecified state: all operations with no preconditions (like a.empty(), a.clear(), a = "new", ~string) are valid
D. Using a in any way after std::move is Undefined Behavior

**Standard Answer (C):** a is in a valid but unspecified state: all operations with no preconditions (like a.empty(), a.clear(), a = "new", ~string) are valid

**Why:** Standard library types leave moved-from objects in a valid but unspecified state ([lib.types.movedfrom]). While small-string optimization means a might NOT even be empty, you may safely inspect size(), call clear(), reassign, or destroy a.

---
Attribution: content from https://en.cppreference.com/w/cpp/container/vector (cppreference.com), licensed under CC-BY-SA 3.0 and GFDL. Modified: converted to markdown, study notes added. Offline snapshot of 9 February 2025.