← C++ Index

📦 <vector> — std::vector — Dynamic Array Container

The most widely used C++ container — a resizable array with O(1) random access and amortized O(1) push_back. Prefer over raw arrays.

Include: #include <vector> | Namespace: std | Compile: g++ -Wall -std=c++17 ...

📋 Classes, Functions & Symbols

NameType / SignatureDescription
std::vector<T>class templateDynamic array of type T
v.push_back(x)voidAppend element x to the end
v.pop_back()voidRemove the last element
v.emplace_back(…)T &Construct element in-place at end (C++11)
v.size()size_tNumber of elements
v.capacity()size_tCurrent allocated capacity
v.empty()boolTrue if vector has no elements
v.clear()voidRemove all elements
v.resize(n)voidResize to n elements
v.reserve(n)voidPre-allocate space for n elements
v.shrink_to_fit()voidRelease excess capacity (C++11)
v.front()T &Reference to first element
v.back()T &Reference to last element
v.at(i)T &Element at index i with bounds check
v[i]T &Element at index i (no bounds check)
v.begin()/v.end()iteratorIterators for range traversal
v.insert(pos, x)iteratorInsert x before position pos
v.erase(pos)iteratorRemove element at position pos
v.data()T *Pointer to underlying C array

💡 Example Program

Copy, save as demo.cpp, and compile with the command at the bottom.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v = {5, 3, 8, 1, 9, 2};
    v.push_back(7);
    v.emplace_back(4);

    cout << "Elements: ";
    for (int x : v) cout << x << " ";
    cout << "\n";

    sort(v.begin(), v.end());
    cout << "Sorted:   ";
    for (int x : v) cout << x << " ";
    cout << "\n";

    auto it = find(v.begin(), v.end(), 8);
    if (it != v.end())
        cout << "Found 8 at index " << (it - v.begin()) << "\n";

    v.erase(remove(v.begin(), v.end(), 8), v.end());
    cout << "After removing 8: ";
    for (int x : v) cout << x << " ";
    cout << "\nSize=" << v.size() << " Capacity=" << v.capacity() << "\n";
    return 0;
}
// Compile: g++ -Wall -std=c++17 -o vector_demo vector_demo.cpp

← <string>  |  🏠 Index  |  <map> →