std::vector
Dynamic array container
Interview Relevant: Most used container
std::vector
Dynamic array with automatic resizing. O(1) random access.
Code Examples
Comprehensive vector operations.
cpp
1#include <vector>
2
3// Creation
4vector<int> v1; // Empty
5vector<int> v2(5); // 5 zeros
6vector<int> v3(5, 10); // 5 tens
7vector<int> v4 = {1, 2, 3, 4, 5}; // Initializer list
8
9// Add elements
10v1.push_back(10); // Add to end - O(1) amortized
11v1.emplace_back(20); // Construct in place
12
13// Access
14int x = v4[0]; // No bounds check
15int y = v4.at(0); // With bounds check
16int first = v4.front();
17int last = v4.back();
18
19// Size
20v4.size(); // Number of elements
21v4.capacity(); // Allocated space
22v4.empty(); // Is empty?
23v4.reserve(100); // Pre-allocate
24v4.shrink_to_fit(); // Reduce capacity
25
26// Modify
27v4.pop_back(); // Remove last
28v4.insert(v4.begin(), 0); // Insert at position
29v4.erase(v4.begin()); // Remove at position
30v4.clear(); // Remove all
31
32// 2D vector
33vector<vector<int>> matrix(3, vector<int>(4, 0));