std::vector
Dynamic Arrays in C++
Master the most essential container in the C++ Standard Library: std::vector. Learn to create, modify, and iterate over dynamic arrays with confidence.
What Is std::vector?
A std::vector is a sequence container from the C++ Standard Library that stores elements in contiguous memory, just like a plain array, but can grow and shrink at runtime. You never need to declare a fixed size up front.
How Memory Works Inside
Why Use std::vector?
Core Declaration Syntax
#include <vector> // Empty vector of ints std::vector<int> nums; // Initialize with values std::vector<int> scores = {90, 85, 92, 78}; // 5 elements, all initialized to 0 std::vector<int> zeros(5, 0); // Vector of strings std::vector<std::string> names = {"Alice", "Bob"};
Essential Operations
std::vector vs Plain Array
| std::vector | int arr[N] | |
|---|---|---|
| Size | Dynamic: grows at runtime | Fixed at compile time |
| Memory | Heap (automatic) | Stack (usually) |
| Bounds Check | .at(i) throws exception | None: undefined behavior |
| Knows Its Size | .size() always available | Must track separately |
| Copy | Simple: v2 = v1; | Manual loop or memcpy |
| Performance | Same contiguous access | Same contiguous access |
Step-by-Step Usage Pattern
Example 1: Building a Vector
#include <vector> #include <iostream> int main() { std::vector<int> grades; grades.push_back(88); grades.push_back(95); grades.push_back(72); grades.push_back(91); // Print all grades for (int g : grades) { std::cout << g << " "; } // Output: 88 95 72 91 }
Example 2: Access and Modify
std::vector<int> v = {10, 20, 30, 40, 50}; // Read element at index 2 int x = v[2]; // x = 30 // Modify element at index 0 v[0] = 99; // v is now {99, 20, 30, 40, 50} // Safe access with bounds checking int y = v.at(4); // y = 50 // This would throw std::out_of_range: // int z = v.at(10); // Get first and last elements int first = v.front(); // 99 int last = v.back(); // 50
Example 3: Algorithms with Vectors
#include <vector> #include <algorithm> #include <numeric> std::vector<int> v = {5, 2, 8, 1, 9, 3}; // Sort ascending std::sort(v.begin(), v.end()); // v = {1, 2, 3, 5, 8, 9} // Find an element auto it = std::find(v.begin(), v.end(), 8); // Sum all elements int total = std::accumulate(v.begin(), v.end(), 0); // total = 28
Three Ways to Iterate
cout << x;
}
i < v.size(); i++) {
cout << v[i];
}
it != v.end(); ++it) {
cout << *it;
}
Time Complexity of Operations
| Operation | Complexity | Notes |
|---|---|---|
| push_back() | Amortized \( O(1) \) | Occasional reallocation |
| pop_back() | \( O(1) \) | No reallocation |
| operator[] / at() | \( O(1) \) | Direct pointer arithmetic |
| insert(pos, val) | \( O(n) \) | Shifts elements right |
| erase(pos) | \( O(n) \) | Shifts elements left |
| size() / empty() | \( O(1) \) | Stored internally |
The Erase-Remove Idiom
Removing elements by value is a two-step process in C++. std::remove shifts unwanted elements to the end, and erase actually shrinks the vector.
std::vector<int> v = {1, 3, 2, 3, 5, 3, 7}; // Remove all 3s v.erase( std::remove(v.begin(), v.end(), 3), v.end() ); // v = {1, 2, 5, 7}
Common Mistakes
Quick Reference Cheat Sheet
| Method | What It Does | Returns |
|---|---|---|
| push_back(val) | Adds val to end | void |
| pop_back() | Removes last element | void |
| size() | Current element count | size_t |
| empty() | Checks if size is 0 | bool |
| at(i) | Bounds-checked access | T& |
| front() / back() | First / last element | T& |
| clear() | Removes all elements | void |
| reserve(n) | Pre-allocates capacity | void |
Question 1 of 5
What is the time complexity of accessing an element with v[i] in a std::vector?
Question 2 of 5
What happens when you call v.at(10) on a vector with only 5 elements?
Question 3 of 5
After this code runs, what does v contain?
std::vector<int> v = {1, 2, 3}; v.push_back(4); v.pop_back(); v.pop_back();
Question 4 of 5
Which loop syntax is the most idiomatic modern C++ way to iterate over a vector?
Question 5 of 5
Why is inserting an element in the middle of a std::vector \( O(n) \)?