Skip to content

C++ <vector> API

C++ std::vector — a contiguous, dynamically-resizable array with O(1) random access.

1 class · 7 methods

std::vector

7 methods

A sequence container that encapsulates dynamic size arrays.

std::vector::push_back(const T& value)

Appends the given element value to the end of the container.

Parameters

NameTypeDescription
valueconst T&Value to append.

Returns

void

Example

cpp
#include <vector>
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
// v == {1, 2, 3}
std::vector::size() const noexcept -> size_t

Returns the number of elements currently in the container.

Returns

size_t

Example

cpp
std::vector<int> v = {1, 2, 3};
size_t n = v.size();  // 3
std::vector::at(size_t pos) -> reference

Returns a reference to the element at pos with bounds checking (throws std::out_of_range).

Parameters

NameTypeDescription
possize_tPosition of the element.

Returns

reference

Example

cpp
std::vector<int> v = {10, 20, 30};
int x = v.at(1);  // 20
// v.at(10);  // throws std::out_of_range
std::vector::pop_back()

Removes the last element of the container. Calling on an empty vector is undefined.

Returns

void

Example

cpp
std::vector<int> v = {1, 2, 3};
v.pop_back();
// v == {1, 2}
std::vector::empty() const noexcept -> bool

Returns true if the container has no elements, false otherwise.

Returns

bool

Example

cpp
std::vector<int> v;
if (v.empty()) {
    std::cout << "no elements\n";
}
std::vector::clear() noexcept

Erases all elements from the container, leaving size() == 0.

Returns

void

Example

cpp
std::vector<int> v = {1, 2, 3};
v.clear();
// v.size() == 0
std::vector::begin() noexcept -> iterator

Returns an iterator to the first element of the container.

Returns

iterator

Example

cpp
std::vector<int> v = {1, 2, 3};
for (auto it = v.begin(); it != v.end(); ++it) {
    std::cout << *it << " ";
}
// prints: 1 2 3