std::vector
7 methodsA 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
| Name | Type | Description |
|---|---|---|
| value | const 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_tReturns 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(); // 3std::vector::at(size_t pos) -> referenceReturns a reference to the element at pos with bounds checking (throws std::out_of_range).
Parameters
| Name | Type | Description |
|---|---|---|
| pos | size_t | Position 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_rangestd::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 -> boolReturns 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() noexceptErases all elements from the container, leaving size() == 0.
Returns
void
Example
cpp
std::vector<int> v = {1, 2, 3};
v.clear();
// v.size() == 0std::vector::begin() noexcept -> iteratorReturns 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