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


C++ deque shrink_to_fit用法及代码示例


deque::shrink_to_fit()是C++ STL中的内置函数,它会减小容器的容量以适应其大小,并破坏超出该容量的所有元素。此函数不会减小容器的尺寸。当为容器分配的内存超过了所需的内存量时,将使用此函数,然后此函数释放已分配的额外内存量。

用法:

deque_name.shrink_to_fit()

参数:该函数不接受任何参数。
返回值:该函数不返回任何内容。



以下示例程序旨在说明上述函数:
Example-1

// C++ program to illustrate 
// the deque::shrink_to_fit() 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
  
    // Initialized deque 
    deque<int> d(10); 
  
    for (int i = 0; i < 5; i++) 
        d[i] = i; 
  
    // Initial deque 
    cout << " Deque size initially:" << d.size(); 
  
    cout << "\n Deque  elements are:"; 
    for (int i = 0; i < 10; i++) 
        cout << d[i] << " "; 
  
    // changes the size of the Deque 
    // but does not destroys the elements 
    d.resize(7); 
  
    cout << "\n Deque size after resize(7):"
         << d.size(); 
  
    cout << "\n Deque elements after resize(7) are:"; 
    for (int i = 0; i < 10; i++) 
        cout << d[i] << " "; 
  
    // Shrinks to the size 
    // till which elements are 
    // destroys the elements after 5 
    d.shrink_to_fit(); 
  
    cout << "\n Deque size after shrink_to_fit():"
         << d.size(); 
  
    cout << "\n Deque elements after shrink_to_fit() are:"; 
    for (int i = 0; i < 10; i++) 
        cout << d[i] << " "; 
  
    return 0; 
}
输出:
Deque size initially:10
Deque  elements are:0 1 2 3 4 0 0 0 0 0 
Deque size after resize(7):7
Deque elements after resize(7) are:0 1 2 3 4 0 0 0 0 0 
Deque size after shrink_to_fit():7
Deque elements after shrink_to_fit() are:0 1 2 3 4 0 0 0 0 0

示例2

// C++ program to illustrate 
// the deque::shrink_to_fit() 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    // creating a deque 
    deque<int> d(100); 
  
    cout << "Size of d is:" << d.size() << endl; 
  
    // resizing 
    d.resize(20); 
  
    cout << "Size of d after resize is:" << d.size() << endl; 
  
    d.shrink_to_fit(); 
    return 0; 
}
输出:
Size of d is:100
Size of d after resize is:20

注意:shrink_to_fit()函数在容器大小不断变化的向量中非常有用。




相关用法


注:本文由纯净天空筛选整理自ankit15697大神的英文原创作品 deque shrink_to_fit in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。