C++ Vectors
π¦ C++ Vectors
std::vector is a dynamic array provided by the C++ Standard Template Library (STL).
It can grow or shrink at runtime and offers fast random access, making it one of the most commonly used containers in C++.
πΉ 1. Why Use vector?
Dynamic size (unlike arrays)
Contiguous memory (fast access)
Automatic memory management
Rich set of member functions
Works seamlessly with STL algorithms
πΉ 2. Include Header
πΉ 3. Declaring a Vector
With initialization:
With size:
πΉ 4. Adding Elements
πΉ 5. Accessing Elements
πΉ 6. Traversing a Vector
Using Index
Using Range-based Loop
Using Iterator
πΉ 7. Removing Elements
πΉ 8. Size vs Capacity
Reserve capacity:
πΉ 9. Insert Elements
Insert multiple:
πΉ 10. Clear a Vector
πΉ 11. Sorting a Vector
Descending:
πΉ 12. Vector of Objects
πΉ 13. 2D Vector
πΉ 14. Time Complexity
| Operation | Complexity |
|---|---|
| Access | O(1) |
| push_back | O(1) amortized |
| insert/erase (middle) | O(n) |
| pop_back | O(1) |
β Common Mistakes
β Use at() if unsure.
π Summary
vectoris a dynamic arrayFast access, flexible size
Use
push_back()to addUse
erase()to removesize()vscapacity()mattersCore STL container
