C++ Snippet

std::vector Quick Reference

Difficulty: Easy

`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.

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

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.