当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ deque resize()用法及代码示例


deque::resize() 是 C++ STL 中的一个内置函数,它改变双端队列的大小。如果给定大小大于当前大小,则在双端队列末尾插入新元素。如果给定大小小于当前大小,然后额外的元素被销毁。

用法:

deque_name.resize(n)

范围:该函数只接受一个强制参数 n,它指定双端队列的大小。

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

以下示例程序旨在说明上述函数:

程序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)


相关用法


注:本文由纯净天空筛选整理自rupesh_rao大神的英文原创作品 deque resize() function in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。