当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ vector::shrink_to_fit()用法及代码示例


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()



相关用法


注:本文由纯净天空筛选整理自 vector::shrink_to_fit() function with example in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。