std::basic_string<CharT,Traits,Allocator>::clear
来自 cppreference.cn
< cpp | string | basic string
void clear(); |
(noexcept since C++11) (C++11 起无异常抛出) (constexpr since C++20) (C++20 起constexpr) |
|
从字符串中移除所有字符,如同执行 erase(begin(), end())。
所有指针、引用和迭代器均失效。
内容 |
[edit] 参数
(无)
[edit] 返回值
(无)
[edit] 注意
与 std::vector::clear 不同,C++ 标准没有明确要求 capacity 会被此函数改变,但现有的实现都不会改变容量。这意味着它们不会释放已分配的内存(另请参见 shrink_to_fit)。
[edit] 复杂度
与字符串的大小呈线性关系,尽管现有的实现以常数时间运行。
[edit] 示例
运行此代码
#include <cassert> #include <iostream> #include <string> int main() { std::string s{"Exemplar"}; std::string::size_type const capacity = s.capacity(); s.clear(); assert(s.empty()); assert(s.size() == 0); std::cout << std::boolalpha << (s.capacity() == capacity) << '\n'; }
可能的输出
true
[edit] 参见
移除字符 (公共成员函数) |