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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。