Namespaces
Variants

std::basic_string<CharT,Traits,Allocator>:: clear

From cppreference.net
std::basic_string
void clear ( ) ;
(自 C++11 起为 noexcept)
(自 C++20 起为 constexpr)

移除字符串中的所有字符,效果等同于执行 erase ( begin ( ) , end ( ) )

所有指针、引用和迭代器均会失效。

目录

参数

(无)

返回值

(无)

注释

std::vector::clear 不同,C++ 标准并未明确要求此函数保持 capacity 不变,但现有实现均未改变容量。这意味着它们不会释放已分配的内存(另请参阅 shrink_to_fit )。

复杂度

线性于字符串的大小,尽管现有实现以恒定时间运行。

示例

#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

参见

移除字符
(公开成员函数)