std::vector<T,Allocator>:: clear
From cppreference.net
C++
Containers library
|
(C++17)
|
||||
| Sequence | ||||
|
(C++11)
|
||||
|
(C++26)
|
||||
|
(C++26)
|
||||
|
(C++11)
|
||||
| Associative | ||||
| Unordered associative | ||||
|
(C++11)
|
||||
|
(C++11)
|
||||
|
(C++11)
|
||||
|
(C++11)
|
||||
| Adaptors | ||||
|
(C++23)
|
||||
|
(C++23)
|
||||
|
(C++23)
|
||||
|
(C++23)
|
||||
| Views | ||||
|
(C++20)
|
||||
|
(C++23)
|
||||
| Tables | ||||
| Iterator invalidation | ||||
| Member function table | ||||
| Non-member function table |
std::vector
| Member types | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Member functions | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Non-member functions | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Deduction guides (C++17) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
void
clear
(
)
;
|
(自 C++11 起为 noexcept)
(自 C++20 起为 constexpr) |
|
从容器中擦除所有元素。此调用后, size() 返回零。
使所有指向容器元素的引用、指针和迭代器失效。 所有尾后迭代器也会失效。
目录 |
复杂度
与容器大小成线性关系,即元素数量成正比。
注释
调用
clear()
不会影响
capacity()
的结果。标准对容量变更的限制规定在
reserve()
的规范中,具体参见
Stack Overflow
。
示例
运行此代码
#include <iostream> #include <string_view> #include <vector> void print_info(std::string_view rem, const std::vector<int>& v) { std::cout << rem << "{ "; for (const auto& value : v) std::cout << value << ' '; std::cout << "}\n"; std::cout << "Size=" << v.size() << ", Capacity=" << v.capacity() << '\n'; } int main() { std::vector<int> container{1, 2, 3}; print_info("Before clear: ", container); container.clear(); print_info("After clear: ", container); }
输出:
Before clear: { 1 2 3 }
Size=3, Capacity=3
After clear: { }
Size=0, Capacity=3
缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的C++标准。
| 缺陷报告 | 适用范围 | 发布行为 | 正确行为 |
|---|---|---|---|
| LWG 2231 | C++11 | C++11中错误地遗漏了复杂度保证 | 复杂度确认为线性 |
参见
|
擦除元素
(公开成员函数) |