C++ vector::resize() 函數
vector::resize() 是 "vector" 頭文件的庫函數,用於調整向量的大小,它接受更新的元素數量和默認值(可選)並調整向量容器的大小。
注意:要使用矢量,請包括<vector>
標題。
vector::resize() 函數的語法
vector::resize();
參數: n
- 是更新後的尺寸,val
- 是分配給新大小的默認值,並且value_type()
- 它是容器的值類型(第一個模板參數的類型的引用)。
返回值: void
- 它什麽都不返回。
例:
Input: vector<int> vector1{ 1, 2, 3, 4, 5 }; Function call: cout << vector1.resize(10); Output: //if we print elements 1 2 3 4 5 0 0 0 0 0
C++程序演示vector::resize()函數的例子
//C++ STL program to demonstrate example of
//vector::resize() function
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v1;
//printing the size of the vector
cout << "Total number of elements:" << v1.size() << endl;
//pushing elements
v1.push_back(10);
v1.push_back(20);
v1.push_back(30);
v1.push_back(40);
v1.push_back(50);
//printing the size of the vector
cout << "Total number of elements:" << v1.size() << endl;
//printing the elements
cout << "vector elements are:";
for (int x:v1)
cout << x << " ";
cout << endl;
//resizing the size with default value
//and printing the elements
v1.resize(8, 99);
//printing the size of the vector
cout << "Total number of elements:" << v1.size() << endl;
//printing the elements
cout << "vector elements are:";
for (int x:v1)
cout << x << " ";
cout << endl;
//resizing the size without default value
//and printing the elements
v1.resize(10);
//printing the size of the vector
cout << "Total number of elements:" << v1.size() << endl;
//printing the elements
cout << "vector elements are:";
for (int x:v1)
cout << x << " ";
cout << endl;
return 0;
}
輸出
Total number of elements:0 Total number of elements:5 vector elements are:10 20 30 40 50 Total number of elements:8 vector elements are:10 20 30 40 50 99 99 99 Total number of elements:10 vector elements are:10 20 30 40 50 99 99 99 0 0
參考:C++ vector::resize()
相關用法
- C++ vector::reserve()用法及代碼示例
- C++ vector::rend()用法及代碼示例
- C++ vector::rbegin()用法及代碼示例
- C++ vector::max_size()用法及代碼示例
- C++ vector::pop_back()用法及代碼示例
- C++ vector::crend()用法及代碼示例
- C++ vector::push_back()用法及代碼示例
- C++ vector::emplace_back用法及代碼示例
- C++ vector::at()用法及代碼示例
- C++ vector::swap()用法及代碼示例
- C++ vector::shrink_to_fit()用法及代碼示例
- C++ vector::cbegin()用法及代碼示例
- C++ vector::back()用法及代碼示例
- C++ vector::assign()用法及代碼示例
- C++ vector::begin()用法及代碼示例
- C++ vector::cend()用法及代碼示例
- C++ vector::operator[]用法及代碼示例
- C++ vector::clear()用法及代碼示例
- C++ vector::cbegin()、vector::cend()用法及代碼示例
- C++ vector::empty()用法及代碼示例
注:本文由純淨天空篩選整理自 vector::resize() function with example in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。