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

出自cppreference.com
< cpp‎ | string‎ | basic string
 
 
 
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

[編輯] 參閱

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