std::map
7 methods一个有序的关联容器,包含具有唯一键的键值对,按键排序。
std::vector::push_back(const T& value)插入一个 {key, value} 对。返回 {iterator, bool},如果键已存在则 bool 为 false。
Parameters
| Name | Type | Description |
|---|---|---|
| val | const 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(); // 3std::vector::at(size_t pos) -> reference返回容器中元素的数量。
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()移除键为 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() == 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