On this page
std::vector
Prev: containers | Up: containers | Next: std::string
Rel: std::span, std::array, Move Semantics
Ref: cppreference — std::vector
Tags: #public #prog #cpp #stdlib #containers #tier/core
Overview
std::vector<T> (<vector>) is a contiguous, dynamically resizable array. Because elements live adjacent in memory, it is cache-friendly and should be your default sequence container in C++.
Complexity & Idioms
- Random access (
v[i],v.at(i)): O(1) (at()throwsstd::out_of_range). - Append (
push_back,emplace_back): Amortized O(1); callv.reserve(n)when the size is known to avoid repeated reallocations. - Reallocation invalidates all existing pointers, references, and iterators into the vector.
#include <vector>
std::vector<int> nums;
nums.reserve(4);
nums.push_back(10);
nums.emplace_back(20);
Gotcha
std::vector<bool>is a bit-packed specialization that does not return realbool&references; usestd::vector<std::uint8_t>orstd::bitsetif you need normal reference semantics.
Linked from
Related notes
- tuts/cpp/stdlib/containers/array Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/span Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/string Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib
- tuts/cpp/stdlib/algorithm_and_ranges/sort links to this page; shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/transform links to this page; shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/builtins/move_semantics Linked here; shared tags: #cpp, #prog, #tier
- tuts/cpp/builtins/new_and_delete links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/tutorials/ranges_and_span_data_pipeline links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/stdlib/containers/expected shared tags: #containers, #cpp, #prog, #stdlib, #tier