C++ vector::resize() 函数



C++ vector::resize() 函数用于通过指定元素数量 (n) 调整容器大小。如果 n 小于当前向量的大小,则内容仅限于向量的前 n 个元素。resize() 函数的时间复杂度为线性。

如果 n 大于当前向量的大小,则新元素将添加到向量的末尾。如果指定了 val,则新元素将使用 val 初始化;否则,它们将进行值初始化。

语法

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

void resize (size_type n);void resize (size_type n, const value_type& val);

参数

  • n - 表示新的容器大小,以元素数量表示。
  • val - 表示用于初始化新元素的值。

示例 1

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

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

int main(void) {
   vector<int> v;
   cout << "Initial vector size = " << v.size() << endl;
   v.resize(5, 10);
   cout << "Vector size after resize = " << v.size() << endl;
   cout << "Vector contains following elements" << endl;
   for (int i = 0; i < v.size(); ++i)
      cout << v[i] << endl;
   return 0;
}

输出

当我们编译并运行上述程序时,将产生以下结果:

Initial vector size = 0
Vector size after resize = 5
Vector contains following elements
10
10
10
10
10

示例 2

考虑另一种情况,我们将使用字符串类型并减小向量的大小。

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

int main(){
   vector<string> car = {"AUDI", "BUCATI", "CHERON", "BMW","BENZ"};
   cout << "current size of the vector: " << car.size() << endl;
   car.push_back("RS7");
   car.push_back("Q5");
   car.push_back("LAMBO");
   cout << "current size of the vector after insertion: " << car.size() << endl;
   car.resize(3);
   cout << "current size of the vector after resize: " << car.size() << endl;
   return 0;
}

输出

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

current size of the vector: 5
current size of the vector after insertion: 8
current size of the vector after resize: 3

示例 3

在以下示例中,我们将使用 n 大于当前向量的大小。

#include<iostream>  
#include<vector>  
using namespace std;
  
int main(){
   vector<string>  bike{"RX100","ACCESS","ACTIVA"};  
   cout<<"Elements before resize:"<<endl;  
   for(int i=0;i<bike.size();i++)  
      cout<<bike[i]<<" "<<endl;  
   bike.resize(5,"VESPA");  
   cout<<"Elements after resize:"<<endl;  
   for(int i=0;i<bike.size();i++)  
      cout<<bike[i]<<" "<<endl;  
   return 0;
}  

输出

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

Elements before resize:
RX100 
ACCESS 
ACTIVA 
Elements after resize:
RX100 
ACCESS 
ACTIVA 
VESPA 
VESPA 

示例 4

以下是示例,我们将使用浮点类型并使用值调整向量大小。

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

int main(){
   vector<float> tutorial = {1.2,2.3,0.4,0.5};
   cout << "Vector values before resize:\n";
   for(int i = 0; i < tutorial.size(); ++i)
      cout << tutorial[i] << " ";
   cout << "\n";
   tutorial.resize(6,0.67);
   cout << "Vector values after resize:\n";
   for(int i = 0; i < tutorial.size(); ++i)
      cout << tutorial[i] << " ";
   cout << "\n";
   return 0;
}

输出

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

Vector values before resize:
1.2 2.3 0.4 0.5 
Vector values after resize:
1.2 2.3 0.4 0.5 0.67 0.67 
广告