vector<data_type> arr — full practical reference ↑ top
#include <vector>
using namespace std;
vector<int> arr;
vector<int> a = {10, 20, 30};
vector<int> b(5); // 5 integers, initialized to 0
vector<int> c(5, 7); // {7, 7, 7, 7, 7}
| Task | Syntax | Meaning |
| Add at end | arr.push_back(x); | Append a copy/move of x |
| Construct at end | arr.emplace_back(args...); | Construct element directly at end |
| Insert before position | arr.insert(arr.begin()+i, x); | Insert x before index i |
| Construct before position | arr.emplace(arr.begin()+i, args...); | Construct directly at that position |
| Delete last | arr.pop_back(); | Removes final element; returns nothing |
| Delete index | arr.erase(arr.begin()+i); | Deletes one element |
| Delete range | arr.erase(arr.begin()+l, arr.begin()+r); | Deletes indices [l, r) |
| Replace/update | arr[i] = newValue; | Replace element at index i |
| Read by index | arr[i] | Fast; no bounds checking |
| Checked read | arr.at(i) | Throws if index is invalid |
| First | arr.front() | First element |
| Last | arr.back() | Last element |
| Number of elements | arr.size() | Returns size |
| Empty? | arr.empty() | Boolean |
| Remove everything | arr.clear() | Size becomes 0 |
| Reserve memory | arr.reserve(n) | Capacity at least n |
| Resize | arr.resize(n) | Changes number of elements |
| Capacity | arr.capacity() | Allocated storage before reallocation |
| Iterators | begin(), end(), rbegin(), rend() | Used with algorithms and loops |
Examples
vector<int> arr = {10, 20, 30};
arr.push_back(40); // {10,20,30,40}
arr.insert(arr.begin() + 1, 15); // {10,15,20,30,40}
arr[2] = 99; // {10,15,99,30,40}
arr.erase(arr.begin() + 3); // {10,15,99,40}
arr.pop_back(); // {10,15,99}
cout << arr.front(); // 10
cout << arr.back(); // 99
cout << arr.size(); // 3
Important: a vector does not have push_front().
You can insert at begin(), but that is usually O(n) because existing elements must shift.