C++ vector::shrink_to_fit() 函数



在学习 shrink_to_fit() 函数之前,让我们先了解这两个术语:

  • 容量 (Capacity) − capacity() 函数是一个内置函数,它返回向量的当前存储空间分配,以元素数表示。此容量不一定等于向量的 size。
  • 大小 (Size) − size() 函数用于返回向量容器的大小或容器中元素的数量。capacity() 指示向量当前正在使用的内存量。

shrink_to_fit() 函数指示向量容器将其容量缩小到其大小。换句话说,容量将等于向量容器中包含的实际元素数量。

语法

以下是 C++ vector::shrink_to_fit() 函数的语法:

void shrink_to_fit();

参数

它不接受任何参数。

示例 1

让我们考虑以下示例,我们将使用 shrink_to_fit() 函数。

#include <iostream>
#include <vector>
using namespace std;

int main(void) {
   vector<int> v(128);
   cout << "Initial capacity = " << v.capacity() << endl;
   v.resize(25);
   cout << "Capacity after resize = " << v.capacity() << endl;
   v.shrink_to_fit();
   cout << "Capacity after shrink_to_fit = " << v.capacity() << endl;
   return 0;
}

输出

编译并运行上述程序后,将产生以下结果:

Initial capacity = 128
Capacity after resize = 128
Capacity after shrink_to_fit = 25

示例 2

考虑另一种情况,我们将使用字符串类型并应用 shrink_to_fit() 函数。

#include <iostream>
#include <vector>
using namespace std;

int main(void) {
   vector<string> myvector(50);
   cout << "Initial capacity = " << myvector.capacity() << endl;
   myvector.resize(13);
   cout << "Capacity after resize = " << myvector.capacity() << endl;
   myvector.shrink_to_fit();
   cout << "Capacity after shrink_to_fit = " << myvector.capacity() << endl;
   return 0;
}

输出

运行上述程序后,将产生以下结果:

Initial capacity = 50
Capacity after resize = 50
Capacity after shrink_to_fit = 13

示例 3

在以下示例中,我们将使用 push_back() 函数插入值,然后应用 shrink_to_fit() 函数。

#include <iostream>
#include <vector>
using namespace std;

void print_vector(vector<int> myvector){
   for(int x: myvector)
      cout << x << " ";
}
int main(){
   vector<int> myvector;
   myvector.push_back(11);
   myvector.push_back(22);
   myvector.push_back(33);
   cout << "Actual vector: ";
   print_vector(myvector);
   cout << endl;
   cout << "Capacity of vector is: " << myvector.capacity()<<endl;
   myvector.resize(2);
   cout << "After Resize(2): ";
   print_vector(myvector);
   cout << endl;
   cout << "Capacity of vector is: " << myvector.capacity()<<endl;
   myvector.shrink_to_fit(); 
   cout << "after using shrink_to_fit() fuction vector capacity is: "<<myvector.capacity();
   return 0;
}

输出

执行上述程序后,将产生以下结果:

Actual vector: 11 22 33 
Capacity of vector is: 4
After Resize(2): 11 22 
Capacity of vector is: 4
after using shrink_to_fit() fuction vector capacity is: 2
广告