Skip to content

C++ <vector> API

C++ std::map —— 一个有序的键值对关联容器,以红黑树实现。

1 class · 7 methods

std::map

7 methods

一个有序的关联容器,包含具有唯一键的键值对,按键排序。

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

插入一个 {key, value} 对。返回 {iterator, bool},如果键已存在则 bool 为 false。

Parameters

NameTypeDescription
valconst T&要插入的键值对。

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

返回 k 对应映射值的引用,未找到时抛出 std::out_of_range。

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

返回容器中元素的数量。

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()

移除键为 k 的元素。返回移除的元素数量(0 或 1)。

Returns

void

Example

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

返回键为 k 的元素的迭代器,未找到则返回 end()。

Returns

bool

Example

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

如果容器没有元素则返回 true。

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