The most widely used C++ container — a resizable array with O(1) random access and amortized O(1) push_back. Prefer over raw arrays.
Include: #include <vector> | Namespace: std | Compile: g++ -Wall -std=c++17 ...
| Name | Type / Signature | Description |
|---|---|---|
| std::vector<T> | class template | Dynamic array of type T |
| v.push_back(x) | void | Append element x to the end |
| v.pop_back() | void | Remove the last element |
| v.emplace_back(…) | T & | Construct element in-place at end (C++11) |
| v.size() | size_t | Number of elements |
| v.capacity() | size_t | Current allocated capacity |
| v.empty() | bool | True if vector has no elements |
| v.clear() | void | Remove all elements |
| v.resize(n) | void | Resize to n elements |
| v.reserve(n) | void | Pre-allocate space for n elements |
| v.shrink_to_fit() | void | Release excess capacity (C++11) |
| v.front() | T & | Reference to first element |
| v.back() | T & | Reference to last element |
| v.at(i) | T & | Element at index i with bounds check |
| v[i] | T & | Element at index i (no bounds check) |
| v.begin()/v.end() | iterator | Iterators for range traversal |
| v.insert(pos, x) | iterator | Insert x before position pos |
| v.erase(pos) | iterator | Remove element at position pos |
| v.data() | T * | Pointer to underlying C array |
Copy, save as demo.cpp, and compile with the command at the bottom.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = {5, 3, 8, 1, 9, 2};
v.push_back(7);
v.emplace_back(4);
cout << "Elements: ";
for (int x : v) cout << x << " ";
cout << "\n";
sort(v.begin(), v.end());
cout << "Sorted: ";
for (int x : v) cout << x << " ";
cout << "\n";
auto it = find(v.begin(), v.end(), 8);
if (it != v.end())
cout << "Found 8 at index " << (it - v.begin()) << "\n";
v.erase(remove(v.begin(), v.end(), 8), v.end());
cout << "After removing 8: ";
for (int x : v) cout << x << " ";
cout << "\nSize=" << v.size() << " Capacity=" << v.capacity() << "\n";
return 0;
}
// Compile: g++ -Wall -std=c++17 -o vector_demo vector_demo.cpp← <string> | 🏠 Index | <map> →