C++ Vectors
Dynamic Arrays: Vectors
Vectors are sequence containers representing arrays that can change in size. Just like arrays, vectors use contiguous storage locations for their elements, meaning their elements can also be accessed using offsets on regular pointers, ensuring constant-time access.
Unlike standard arrays, a vector's size can change dynamically. When a vector runs out of capacity, it automatically reallocates a larger memory block, copies the elements, and deallocates the old memory, which can be computationally expensive if done frequently.
To prevent performance issues during growth, you can use the reserve() method to allocate sufficient memory upfront. Common operations include push_back() to insert items, pop_back() to delete the last item, and size() to query the active count.
Understanding iterator invalidation is crucial: modifying a vector's size can cause existing pointers and iterators to point to deallocated memory, leading to undefined behavior if not updated.
Pre-allocating Capacity
Using v.reserve(100) informs the compiler to reserve memory for 100 elements, ensuring that subsequent additions do not trigger memory reallocations.
#include <iostream>
#include <vector>
int main() {
std::vector<int> v;
v.reserve(100);
std::cout << "Capacity: " << v.capacity() << std::endl;
return 0;
}#include <iostream>
#include <vector>
int main() {
std::vector<std::string> names;
names.push_back("Bob");
names.push_back("Charlie");
std::cout << "Size of vector: " << names.size() << std::endl;
std::cout << "First item: " << names[0] << std::endl;
return 0;
}