Table of Contents

<vector>

<vector> provides std::vector<T>, a dynamic array with O(1) amortized append, O(1) random access, and O(n) insertion/deletion in the middle. It grows exponentially as you push elements, minimizing reallocations.

Use vector for almost any sequence of elements; it's the default choice for ordered containers.

Example

This example constructs a vector, appends elements, sorts it, and iterates through the result.

// compile: g++ -std=c++11 -o vectorexample vectorexample.cpp
// run: ./vectorexample
// description: vector construction and operations
 
#include <vector>
#include <algorithm>
#include <iostream>
 
int main() {
    std::vector<int> v = {3, 1, 4, 1, 5};
 
    std::cout << "size: " << v.size() << "\n";
    std::cout << "capacity: " << v.capacity() << "\n";
 
    v.push_back(9);
 
    std::sort(v.begin(), v.end());
 
    std::cout << "sorted: ";
    for (int x : v) std::cout << x << " ";
    std::cout << "\n";
 
    return 0;
}