C++ STL 中的 deque assign() 函式


給定任務是展示 C++ STL 中 deque::assign() 的工作原理。

Deque 是一個雙端佇列。在 C++ 中,deque::assign() 是一個內建函式,用於為 deque 容器分配新值。每次呼叫此函式時,它都會透過替換現有值並相應地更改分配的大小來為 deque 容器分配新值。

語法

deque::assign() 的語法如下:

dequename.assign(<int> size, <int> val)

引數

此函式包含 2 個引數:

第一個是 **size**,表示 deque 容器的大小;第二個是 **val**,表示 deque 容器包含的值。

此外,除了 **size** 和 val 之外,我們還可以將迭代器作為引數來宣告起始和結束點,示例中給出了這兩種表示方式。

返回值

該函式沒有返回值。

示例

Input: dq.assign(5, 1)
Output: deque elements are: 1 1 1 1 1
Input: dq.assign(5, 2)
dq1.assign(dq.start()+2, dq.end())
Output: deque elements are: 2 2 2 2 2
deque elements are: 2 2 2

**解釋** - deque dq 有 5 個元素 2 2 2 2 2,而在 dq1 中,我們跳過從開頭開始的 2 個元素,並從 dq 的第三個元素開始,所以 dq1 有 2 2 2。

使用大小和值

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   deque<int> deq;
   // assign 5 values of 1 each
   deq.assign(5, 1); //here, 5 is the size and 1 is the value
   cout << "deque elements are: ";
   for (auto it = deq.begin(); it != deq.end(); it++)
   cout << *it << " ";
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

deque elements are: 1 1 1 1 1

使用迭代器

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   deque<int> deq;
   // assign 5 values of 2 each
   deq.assign(5, 2);
   cout << "deque elements are: ";
   for (auto it = deq.begin(); it != deq.end(); it++)
   cout << *it << " ";
   deque<int> deq1;
   // assigns all elements from
   // the second position to deque1
   deq1.assign(deq.begin() + 2, deq.end());
   cout << "\ndeque1 elements are: ";
   for (auto it = deq1.begin(); it != deq1.end(); it++)
   cout << *it << " ";
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

deque elements are: 2 2 2 2 2
deque1 elements are: 2 2 2

更新於: 2020-01-20

222 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.