名稱空間
變體
操作

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

來自 cppreference.com
< cpp‎ | string‎ | basic_string
 
 
 
std::basic_string
 
void clear();
(C++11 起無異常丟擲)
(C++20 起為 constexpr)

移除字串中所有字元,如同執行 erase(begin(), end())

所有指標、引用和迭代器都將失效。

目錄

[編輯] 引數

(無)

[編輯] 返回值

(無)

[編輯] 注意

std::vector::clear 不同,C++ 標準並未明確要求此函式不改變 容量,但現有實現並未改變容量。這意味著它們不釋放已分配的記憶體(另請參閱 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

[編輯] 參閱

移除字元
(public member function) [編輯]