Vector
Programming
std::vector is a dynamic array container from the C++ Standard Library that automatically manages memory and can grow and shrink in size. It is one of the most commonly used containers in modern C++.
Basic Usage
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
numbers.push_back(6); // Add an element
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
} Common Operations
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec;
// Adding elements
vec.push_back(10);
vec.push_back(20);
vec.push_back(30);
// Accessing elements
std::cout << "First element: " << vec[0] << std::endl;
std::cout << "Size: " << vec.size() << std::endl;
std::cout << "Capacity: " << vec.capacity() << std::endl;
// Safe access with bounds checking
if (!vec.empty()) {
std::cout << "Last element: " << vec.back() << std::endl;
}
// Inserting at specific position
vec.insert(vec.begin() + 1, 15);
// Removing elements
vec.pop_back();
// Iterating
for (size_t i = 0; i < vec.size(); ++i) {
std::cout << vec[i] << " ";
}
std::cout << std::endl;
return 0;
} Initialization Methods
#include <vector>
int main() {
// Empty vector
std::vector<int> vec1;
// With initial size
std::vector<int> vec2(5); // 5 elements, all zero-initialized
// With initial size and value
std::vector<int> vec3(5, 10); // 5 elements, all set to 10
// From initializer list
std::vector<int> vec4 = {1, 2, 3, 4, 5};
// From another vector (copy)
std::vector<int> vec5(vec4);
// From range
std::vector<int> vec6(vec4.begin(), vec4.begin() + 3);
return 0;
} Performance Considerations
- Time Complexity:
- Access: O(1)
- Insertion at end: O(1) amortized
- Insertion at beginning/middle: O(n)
- Deletion: O(n) for beginning/middle, O(1) for end
- Memory: Vectors may allocate more memory than needed (capacity vs size) to avoid frequent reallocations
- Reserve: Use
reserve()when you know the approximate size to avoid reallocations
Best Practices
- Use
at()for bounds-checked access in debug builds,[]for performance-critical code - Prefer range-based for loops:
for (const auto& elem : vec) - Use
reserve()when you know the size in advance - Use
emplace_back()instead ofpush_back()for complex types to avoid unnecessary copies - Consider
std::arrayfor fixed-size containers
Common Pitfalls
- Accessing elements with
[]without checking bounds (useat()for safety) - Using
size()in loops with signed integers (usesize_tor compare withsize()) - Invalidating iterators by modifying the vector during iteration
- Not reserving capacity when you know the size, causing multiple reallocations
Advantages over C-style Arrays
- Dynamic size (can grow/shrink)
- Automatic memory management
- Rich set of member functions
- Bounds checking with
at() - Iterator support for STL algorithms
- RAII (automatic cleanup when going out of scope)
Output
1 2 3 4 5 6