vector::shrink_to_fit()是C++ STL中的內置函數,可減小容器的容量以適應其大小,並破壞超出該容量的所有元素。
用法:
vector_name.shrink_to_fit()
參數:該函數不接受任何參數。
返回值:該函數不返回任何內容。
以下示例程序旨在說明上述函數:
// C++ program to illustrate
// the vector::shrink_to_fit()
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Initialized vector
vector<int> v(10);
for (int i = 0; i < 10; i++)
v[i] = i;
// Initial vector
cout << "Vector size initially: " << v.size();
cout << "\nVector elements are: ";
for (int i = 0; i < 10; i++)
cout << v[i] << " ";
// changes the size of the Vector
// but does not destroys the elements
v.resize(5);
cout << "\n\nVector size after resize(5): "
<< v.size();
cout << "\nVector elements after resize(5) are: ";
for (int i = 0; i < 10; i++)
cout << v[i] << " ";
// Shrinks to the size
// till which elements are
// destroys the elements after 5
v.shrink_to_fit();
cout << "\n\nVector size after shrink_to_fit(): "
<< v.size();
cout << "\nVector elements after shrink_to_fit() are: ";
for (int i = 0; i < 10; i++)
cout << v[i] << " ";
return 0;
}
輸出:
Vector size initially: 10 Vector elements are: 0 1 2 3 4 5 6 7 8 9 Vector size after resize(5): 5 Vector elements after resize(5) are: 0 1 2 3 4 5 6 7 8 9 Vector size after shrink_to_fit(): 5 Vector elements after shrink_to_fit() are: 0 1 2 3 4 0 127889 0 0 0
相關用法
- C++ vector capacity()用法及代碼示例
- C++ vector insert()用法及代碼示例
- C++ vector data()用法及代碼示例
- C++ vector max_size()用法及代碼示例
- C++ vector emplace()用法及代碼示例
- C++ vector rbegin()、rend()用法及代碼示例
- C++ vector::push_back()、vector::pop_back()用法及代碼示例
- C++ vector::cbegin()、vector::cend()用法及代碼示例
- C++ vector::front()、vector::back()用法及代碼示例
- C++ vector::empty()、vector::size()用法及代碼示例
- C++ vector::at()、vector::swap()用法及代碼示例
- C++ vector::begin()、vector::end()用法及代碼示例
注:本文由純淨天空篩選整理自Twinkl Bajaj大神的英文原創作品 vector shrink_to_fit() function in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。