stl January 25, 2026 β€’ 2 min read

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

OperationTime Complexity
push_backAmortized O(1)
pop_backO(1)
insertO(n)
eraseO(n)
operator[]O(1)
findO(n)

Best Practice: Use reserve() when you know the approximate size to avoid unnecessary reallocations.

Related Articles