shrink_to_fit
C ++ vector :: shrink_to_fit()函数 (C++ vector::shrink_to_fit() function)
vector::shrink_to_fit() is a library function of "vector" header, which is used to reduce capacity to fit size. Refer to example to understand in details.
vector :: shrink_to_fit()是“ vector”标头的库函数,用于减少容量以适应大小。 请参阅示例以详细了解。
This may lead to reallocation, but elements don't alter.
这可能会导致重新分配,但元素不会改变。
Note: To use vector, include <vector> header.
注意:要使用向量,请包含<vector>标头。
Syntax of vector::shrink_to_fit() function
vector :: shrink_to_fit()函数的语法
vector::shrink_to_fit();
Parameter(s): none – It accepts nothing.
参数: 无 –不接受任何内容。
Return value: void – It returns nothing.
返回值: void –不返回任何内容。
Example:
例:
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
C ++程序演示vector :: shrink_to_fit()函数的示例 (C++ program to demonstrate example of vector::shrink_to_fit() function)
#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;
}
Output
输出量
...capacity of the vector: 50...
...After resizing...
capacity of the vector: 50
...After using shrink_to_fit...
capacity of the vector: 10
Reference: C++ vector::shrink_to_fit()
参考: C ++ vector :: shrink_to_fit()
翻译自: https://www.includehelp.com/stl/vector-shrink_to_fit-function-with-example.aspx
shrink_to_fit