📜  C++ STL中的vectorrink_to_fit()函数

📅  最后修改于: 2021-05-30 02:31:26             🧑  作者: Mango

vector :: shrink_to_fit()是C++ STL中的内置函数,可减少容器以适应其大小的容量,并破坏超出容量的所有元素。

句法:

vector_name.shrink_to_fit()

参数:该函数不接受任何参数。

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

下面的程序说明了上述函数:

// C++ program to illustrate
// the vector::shrink_to_fit() 
#include 
using namespace std;
  
int main()
{
  
    // Initialized vector
    vector 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++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”