std::vector in C++: Dynamic Arrays, Capacity, and Common Operations
What is std::vector in C++: Dynamic Arrays, Capacity, and Common Operations? std::vector is a dynamic contiguous array that grows automatically when elements are added. size() is the number of elements currently stored, whereas capacity(...
How does std::vector manage memory, and what is the difference between size and capacity?
Explanation & In-Depth Details
```text
std::vector memory management:
┌──────────────┬───────────────────────────────┬────────────────────────┐
│ [0] [1] [2] │ (Unused Allocated Storage) │ │
└──────────────┴───────────────────────────────┴────────────────────────┘
▲ ▲ ▲
begin() size() / end() capacity()
```
2. Key Operations:
- `push_back(v)` / `emplace_back(args...)`: Amortized $O(1)$ append.
- `reserve(n)`: Allocates capacity in advance without creating elements.
- `shrink_to_fit()`: Frees unused extra capacity.
Code Example
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec;
vec.reserve(5); // Pre-allocate memory for 5 elements
std::cout << "Initial: Size = " << vec.size() << ", Capacity = " << vec.capacity() << "\n";
for (int i = 1; i <= 6; ++i) {
vec.push_back(i * 10);
std::cout << "Added " << i * 10 << " -> Size: " << vec.size()
<< ", Capacity: " << vec.capacity() << "\n";
}
std::cout << "Elements: ";
for (int val : vec) std::cout << val << " ";
std::cout << "\n";
return 0;
}Interview Question & Tips
A: When a vector reallocates memory due to exceeding its capacity during push_back or insert, all existing pointers, references, and iterators to its elements become dangling and invalid.
Q: What is the benefit of `emplace_back` over `push_back`?
A: `emplace_back` constructs the object in-place directly in the vector's allocated storage using forwarded constructor arguments, avoiding temporary object construction and copy/move operations.
Best Practices
• Use `emplace_back()` instead of `push_back()` for non-primitive objects.
• Use `.at(index)` when bounds-checking is required, or `operator[]` for maximum speed in verified loops.
This study reference for std::vector in C++: Dynamic Arrays, Capacity, and Common Operations is curated and verified against recognized curriculum benchmarks, peer-reviewed textbooks, and official technical documentation: