STL Vectors
A complete guide to std::vector β the most commonly used container in the C++ Standard Template Library.
STL Vectors
std::vector is a dynamic array that can grow and shrink in size. Itβs the most commonly used container in C++.
Declaration and Initialization
#include <vector>
#include <iostream>
int main() {
// Empty vector
std::vector<int> v1;
// Vector with initial values
std::vector<int> v2 = {1, 2, 3, 4, 5};
// Vector with size and default value
std::vector<int> v3(5, 0); // {0, 0, 0, 0, 0}
// Copy constructor
std::vector<int> v4(v2);
}
Common Operations
std::vector<int> nums = {10, 20, 30};
// Add elements
nums.push_back(40); // {10, 20, 30, 40}
nums.emplace_back(50); // {10, 20, 30, 40, 50}
// Access elements
int first = nums[0]; // 10 (no bounds check)
int safe = nums.at(1); // 20 (with bounds check)
int last = nums.back(); // 50
// Size
size_t size = nums.size(); // 5
bool empty = nums.empty(); // false
// Remove elements
nums.pop_back(); // Removes 50
nums.erase(nums.begin()); // Removes 10
Iteration
std::vector<std::string> fruits = {"apple", "banana", "cherry"};
// Range-based for (C++11)
for (const auto& fruit : fruits) {
std::cout << fruit << "\n";
}
// Iterator-based
for (auto it = fruits.begin(); it != fruits.end(); ++it) {
std::cout << *it << "\n";
}
// Index-based
for (size_t i = 0; i < fruits.size(); ++i) {
std::cout << fruits[i] << "\n";
}
Performance
| Operation | Time Complexity |
|---|---|
push_back | Amortized O(1) |
pop_back | O(1) |
insert | O(n) |
erase | O(n) |
operator[] | O(1) |
find | O(n) |
Best Practice: Use
reserve()when you know the approximate size to avoid unnecessary reallocations.
Related Articles
Introduction to C++
Getting started with C++ programming β compiler setup, basic syntax, variables, and your first program.
Top 10 Developer Tools in 2026
My curated list of essential developer tools that have transformed my workflow in 2026 β from IDE setups to deployment pipelines.
Why I Switched to Astro for Documentation
My journey from Next.js to Astro for building developer documentation sites β why static-first wins for content-heavy sites.