當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ string shrink_to_fit()用法及代碼示例

C++ 標準模板庫 (STL) 提供了各種用於處理數據結構的有用類和函數,包括用於操作字符串的 std::string 類。 std::string 類的函數之一是 shrink_to_fit() 函數,它允許開發人員將分配給字符串的內存量減少到存儲其當前內容所需的最小量。

在 C++ 中使用字符串時,請務必記住 std::string 類被設計為動態調整大小的字符串。這意味著該類可能會分配比存儲字符串內容實際需要的更多的內存。 shrink_to_fit() 函數允許開發人員將分配給字符串的內存量減少到存儲其當前內容所需的最小量。這在需要考慮內存使用情況的情況下非常有用,例如在 resource-constrained 環境中或處理大量數據時。

需要注意的是,shrink_to_fit() 並不保證容量會減少,它隻是請求減少,但實現可以忽略它。

另外,值得注意的是,這個函數不會改變字符串的大小,隻會改變容量。大小將繼續反映字符串中的字符數,而容量將是為字符串分配的內存量。

我建議使用命名空間 std; C++ 中的指令可能被認為是不好的做法,因為它可能導致命名衝突並使代碼更難以閱讀和理解。

用法:

s.shrink_to_fit();

Parameters: 該函數不接受任何參數。

返回值:該函數不返回任何內容。

可以使用點表示法對字符串對象調用 shrink_to_fit() 函數。例如,以下代碼演示了如何使用shrink_to_fit()函數來減少為字符串分配的內存量:

例子:

C++


// C++ Program to demonstrate the working of
// shrink_to_fit() function
#include <iostream>
#include <string>
//using namespace std;
int main()
{
    // Initializing string
    std::string str = "geeksforgeeks is best";
    // Displaying string
    std::cout << "String is: " << str << "\n";
    // Displaying length of the string
    std::cout << "Size of the string is :" << str.length()
         << "\n";
    // Resizing string using resize()
    str.resize(13);
    // Displaying string
    std::cout << "After resizing string is: " << str << "\n";
    // Displaying capacity of string
    std::cout << "Capacity of the string is :" << str.capacity()
         << "\n";
    // Decreasing the capacity of string
    // using shrink_to_fit()
    str.shrink_to_fit();
    // Displaying new length of the string
    std::cout << "New size of the string is :" << str.length()
         << "\n";
    // Displaying new capacity of string
    std::cout << "New capacity of the string is :"
         << str.capacity() << "\n";
}
輸出
String is: geeksforgeeks is best
Size of the string is :21
After resizing string is: geeksforgeeks
Capacity of the string is :21
New size of the string is :13
New capacity of the string is :13

時間複雜度:O(N),N 是字符串的長度。
輔助空間:O(N),因為字符串是不可變的。



相關用法


注:本文由純淨天空篩選整理自kg_codex大神的英文原創作品 string shrink_to_fit() function in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。