C++ 向量::shrink_to_fit() 函數
vector::shrink_to_fit() 是 "vector" header 的庫函數,用於減少容量以適應大小。詳細參考示例了解。
這可能會導致重新分配,但元素不會改變。
注意:要使用矢量,請包括<vector>
標題。
vector::shrink_to_fit() 函數的語法
vector::shrink_to_fit();
參數: none
——它什麽都不接受。
返回值: void
——它什麽都不返回。
例:
Input: //capacity is initialized to be 100 vector<int> arr(50); arr.capacity() =50 Resize: //doesn't change capacity though arr.resize(10); arr.capacity() =50 shrink_to_fit: //changes capacity as per resize, //thus this practically reduced the capacity arr.shrink_to_fit(); arr.capacity() =10
演示vector::shrink_to_fit()函數示例的C++程序
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> arr(50); //capacity is initialized to be 100
cout << "...capacity of the vector:" << arr.capacity() << "...\n";
arr.resize(10); //doesn't change capacity though
cout << "...After resizing...\n";
cout << "capacity of the vector:" << arr.capacity() << "\n";
arr.shrink_to_fit(); //changes capacity as per resized vector
cout << "...After using shrink_to_fit...\n";
cout << "capacity of the vector:" << arr.capacity() << "\n";
return 0;
}
輸出
...capacity of the vector:50... ...After resizing... capacity of the vector:50 ...After using shrink_to_fit... capacity of the vector:10
參考:C++ 向量::shrink_to_fit()
相關用法
- C++ vector::swap()用法及代碼示例
- C++ vector::size()用法及代碼示例
- C++ vector::max_size()用法及代碼示例
- C++ vector::rbegin()用法及代碼示例
- C++ vector::pop_back()用法及代碼示例
- C++ vector::crend()用法及代碼示例
- C++ vector::push_back()用法及代碼示例
- C++ vector::emplace_back用法及代碼示例
- C++ vector::at()用法及代碼示例
- C++ vector::cbegin()用法及代碼示例
- C++ vector::back()用法及代碼示例
- C++ vector::assign()用法及代碼示例
- C++ vector::begin()用法及代碼示例
- C++ vector::cend()用法及代碼示例
- C++ vector::operator[]用法及代碼示例
- C++ vector::clear()用法及代碼示例
- C++ vector::cbegin()、vector::cend()用法及代碼示例
- C++ vector::empty()用法及代碼示例
- C++ vector::front()、vector::back()用法及代碼示例
- C++ vector::at()、vector::swap()用法及代碼示例
注:本文由純淨天空篩選整理自 vector::shrink_to_fit() function with example in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。