C++ STL中的deque resize()函数
deque::resize() 是C++ STL中的一个内置函数,用于改变deque的大小。
如果给定的大小大于当前大小,则在deque末尾插入新元素。
如果给定的大小小于当前大小,则销毁额外的元素。
语法:
deque_name.resize(n)
参数: 函数只接受一个必需的参数 n ,它指定deque的大小。
返回值: 该函数没有任何返回值。
下面的程序说明了上述函数:
程序1:
// C++ program to illustrate the
// deque::resize() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
deque<int> dq = { 10, 20, 30, 40, 50 };
cout << "Size before resize " << dq.size() << "\n";
// Prints the deque elements
cout << "The contents of deque :";
for (auto it = dq.begin(); it != dq.end(); ++it)
cout << *it << " ";
cout << endl;
// resize to 7
dq.resize(7);
// // Prints the deque elements after resize()
cout << "Size after resize " << dq.size() << "\n";
cout << "The contents of deque :";
for (auto it = dq.begin(); it != dq.end(); ++it)
cout << *it << " ";
return 0;
}
Size before resize 5
The contents of deque :10 20 30 40 50
Size after resize 7
The contents of deque :10 20 30 40 50 0 0
程序2:
// C++ program to illustrate the
// deque::resize() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
deque<int> dq = { 10, 20, 30, 40, 50 };
cout << "Size before resize " << dq.size() << "\n";
// Prints the deque elements
cout << "The contents of deque :";
for (auto it = dq.begin(); it != dq.end(); ++it)
cout << *it << " ";
cout << endl;
// resize to 3
dq.resize(3);
cout << "Size after resize " << dq.size() << "\n";
cout << "The contents of deque :";
for (auto it = dq.begin(); it != dq.end(); ++it)
cout << *it << " ";
return 0;
}
Size before resize 5
The contents of deque :10 20 30 40 50
Size after resize 3
The contents of deque :10 20 30
时间复杂度: O(N)