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


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


描述

C++ 函數std::vector::shrink_to_fit()請求容器減少其容量以適應其大小。

聲明

以下是 std::vector::shrink_to_fit() 函數形式 std::vector 頭文件的聲明。

C++98

void shrink_to_fit();

參數

返回值

示例

下麵的例子展示了 std::vector::shrink_to_fit() 函數的用法。

#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   vector<int> v(128);

   cout << "Initial capacity = " << v.capacity() << endl;

   v.resize(25);
   cout << "Capacity after resize = " << v.capacity() << endl;

   v.shrink_to_fit();
   cout << "Capacity after shrink_to_fit = " << v.capacity() << endl;

   return 0;
}

讓我們編譯並運行上麵的程序,這將產生以下結果——

Initial capacity = 128
Capacity after resize = 128
Capacity after shrink_to_fit = 25

相關用法


注:本文由純淨天空篩選整理自 C++ Vector Library - shrink_to_fit() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。