In C++, std::vector<T> is a container that holds a row of elements of type T. It is a dynamic contiguous array: all elements sit in one memory block, you can grow it at run time, and v[i] is fast.
Two numbers matter: size (how many elements you use) and capacity (how many fit before the next reallocation). Call reserve() when you know the final count so push_back() does not keep reallocating. Include <vector> to use it.
This page teaches what a std::vector is. The Vector Functions index lists every function guide in this series.
Why choose a vector?
Choose a vector for most sequences: random access, fast loops, and fast growth at the back. Prefer std::array when the size is fixed at compile time, std::deque when you need fast inserts at both ends, and std::list when you insert in the middle often with stable iterators.
Syntax
C++ Syntax
Common ways to create and use a std::vector:
C++
#include <iostream>
#include <vector>
std::vector<int> a; // empty
std::vector<int> b = {1, 2, 3}; // three elements
std::vector<int> c(5, 0); // five zeros
b.reserve(10); // prepare capacity
b.push_back(4); // 1 2 3 4
int first = b.front(); // 1
int last = b.back(); // 4
int x = b[2]; // 3, no check
int y = b.at(2); // 3, checked
b.pop_back(); // 1 2 3
std::size_t n = b.size();
std::size_t cap = b.capacity();
Reference
std::vector vs std::array vs std::deque
These three look alike but behave differently. Here is a quick comparison:
Feature
std::vector
std::array
std::deque
Size can grow
Yes
No (fixed)
Yes
Access by index x[i]
Fast
Fast
Fast
Add at the back
Fast
N/A
Fast
Add at the front
Slow (no push_front())
N/A
Fast
Memory layout
One contiguous block
One contiguous block
Several blocks
capacity() / reserve()
Yes
No
No
data() pointer
Yes
Yes
No
Code
C++ Examples
Three short programs that show how std::vector works.
Example 1 — Grow a Vector with push_back()
A first program that adds values at the back, then reads both ends and the size.
std::vector<T> is a container from <vector>. It is a dynamic contiguous array: elements sit in one block, you can grow it with push_back, and you can read elements by index.
size() is how many elements you have. capacity() is how many fit in the current block without reallocating. reserve() raises capacity without changing size.
std::array has a fixed size known at compile time and never grows. std::vector can grow and shrink at run time and tracks size vs capacity.
Both allow index access. A vector uses one contiguous block and is fastest at the back. A deque is fast at both ends but is not one contiguous block and has no capacity() or reserve().
Open the C++ std::vector Functions index. It lists every member function, from push_back() and reserve() to at() and swap(), each with its own tutorial.