Code Snippets
/

std::vector Quick Reference

std::vector Quick Reference

`std::vector` is the default sequence container in C++: a contiguous, dynamically resizing array. This snippet shows the core operations (`push_back`, `emplace_back`, indexed access, range iteration) plus reservation patterns to avoid reallocation churn. Reach for it whenever you would reach for an `ArrayList` in Java or a list literal in Python.

C++
Easy
3 snippets
cpp-stl
cpp-containers
data-structures

1,026 views

5

#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector<int> nums;
    nums.push_back(1);
    nums.push_back(2);
    nums.push_back(3);

    // Indexed access (no bounds check; .at(i) throws std::out_of_range).
    std::cout << "first=" << nums[0] << " size=" << nums.size() << "\n";

    // Range-for is the idiomatic loop.
    for (int n : nums) std::cout << n << " ";
    std::cout << "\n";

    // Initialise from a brace list.
    std::vector<std::string> words = {"alpha", "beta", "gamma"};
    for (const auto& w : words) std::cout << w << "\n";
    return 0;
}

push_back appends one element; the vector's amortised cost is O(1) per insertion because capacity grows geometrically (typically doubling). nums[i] is unchecked: passing an out-of-range index is undefined behaviour, while nums.at(i) throws. Range-for (for (auto x : v)) calls begin()/end() under the hood and is the idiomatic loop in modern C++. Always take by const auto& for non-trivial element types so you avoid an unwanted copy each iteration.