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

出���cppreference.com
 
 
 
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

參閱

移除字符
(公開成員函數) [編輯]