當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。