๐ฆ C++ <vector> โ Dynamic Arrays with std::vector Explained
๐งฒ Introduction โ Why Use <vector> in C++
C++ provides dynamic and resizable arrays using the std::vector class from the <vector> header. Unlike static arrays, vectors can grow or shrink in size at runtime, support random access, and integrate seamlessly with STL algorithms and iterators.
๐ฏ In this guide, youโll learn:
- How to declare and initialize vectors
- Key operations:
push_back(),insert(),erase(),resize() - How vectors compare to arrays and lists
- Performance tips and common use cases
๐ What Is <vector> in C++?
The <vector> header provides the std::vector classโa sequence container representing a dynamic array. It stores elements contiguously in memory, offering fast element access by index and efficient memory management.
Include it with:
#include <vector>
Declare a vector:
std::vector<int> numbers;
๐ป Code Examples โ With Output
โ Declare and Add Elements
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
for (int x : v)
cout << x << " ";
return 0;
}
๐ข Output:
10 20 30
โ Initialize a Vector
vector<int> v1 = {1, 2, 3};
vector<int> v2(5, 100); // 5 elements, all 100
๐ง Common std::vector Methods
| Method | Description |
|---|---|
push_back(val) | Adds element to end |
pop_back() | Removes last element |
insert(pos, val) | Inserts value at position |
erase(pos) | Removes element at position |
clear() | Removes all elements |
size() | Returns number of elements |
resize(n) | Resizes vector to n elements |
front() / back() | First and last elements |
at(index) | Access with bounds checking |
[] | Access without bounds checking |
empty() | Returns true if vector is empty |
๐ Traversing Vectors
โ Using Iterators
for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
cout << *it << " ";
โ Range-Based Loop (C++11+)
for (int x : v)
cout << x << " ";
๐ Vector vs Array vs List
| Feature | vector | array | list |
|---|---|---|---|
| Size flexibility | โ Dynamic | โ Static | โ Dynamic |
| Random access | โ Yes | โ Yes | โ No |
| Insert/remove middle | โ Slow | โ N/A | โ Fast |
| Memory layout | โ Contiguous | โ Contiguous | โ Non-contiguous |
๐ก Best Practices & Tips
๐ Use .reserve(n) to avoid reallocations when size is known
๐ก Prefer emplace_back() over push_back() for efficiency with objects
โ ๏ธ Don’t use [] for unchecked accessโprefer .at() for safety
๐ฆ Use shrink_to_fit() to reduce capacity after large deletions (non-binding)
๐ ๏ธ Use Cases for Vectors
๐งพ Dynamic Lists โ Add/remove items at runtime
๐ Matrix Representations โ Use nested vector<vector<T>>
๐ Stacks/Heaps โ Can act as underlying storage
๐ฎ Game Engines โ Store objects/entities with fast access
๐ File Parsing โ Store lines, tokens, or records
๐ Summary โ Recap & Next Steps
๐ Key Takeaways:
std::vectoris a dynamic array with random access and flexible resizing- Provides rich methods to add, remove, access, and modify data
- Works with STL algorithms and supports iterators
โ๏ธ Real-World Relevance:
Vectors are used everywhereโfrom embedded systems and financial tools to game engines and simulatorsโdue to their simplicity and efficiency.
โ
Next Steps:
Explore โฐ C++ <ctime> to work with timestamps, clocks, and formatted time outputs.
โFAQ โ C++ <vector>
โ Is vector faster than list?
โ
For random access and end insertionsโyes. But for frequent insertions/removals in the middle, use list.
โ Can I access vector elements with indexing?
โ
Yes. Use v[i] or v.at(i) for bounds checking.
โ Does vector automatically manage memory?
โ
Yes. It grows dynamically and manages memory internally.
โ Whatโs the difference between reserve() and resize()?reserve() allocates memory without changing size; resize() changes the number of accessible elements.
โ Can I use std::vector with STL algorithms?
โ
Absolutely. Vectors are fully compatible with algorithms like sort(), find(), and accumulate().
Share Now :
