C++ STL中的queue::swap()
在本文中,我們將討論C++ STL中queue::swap()函式的工作原理、語法和示例。
什麼是C++ STL中的queue?
佇列是一個簡單的序列或資料結構,定義在C++ STL中,以FIFO(先進先出)的方式插入和刪除資料。佇列中的資料以連續的方式儲存。元素插入到末尾,從佇列的開頭刪除。在C++ STL中,已經有一個預定義的佇列模板,以類似於佇列的方式插入和刪除資料。
什麼是queue::swap()?
queue::swap()是C++ STL中的一個內建函式,聲明於
語法
myqueue1.swap(myqueue2);
此函式接受一個引數,即第二個佇列容器,我們希望與關聯的佇列交換內容。
返回值
此函式不返回任何內容。
示例
Input: queue<int> odd = {1, 3, 5};
queue<int> eve = {2. 4. 6};
Output:
Odd: 2 4 6
Eve: 1 3 5示例
#include <iostream>
#include <queue>
using namespace std;
int main(){
queue<int> Queue_1, Queue_2;
for(int i=0 ;i<=5 ;i++){
Queue_1.push(i);
}
for(int i=5 ;i<=10 ;i++){
Queue_2.push(i);
}
//call swap function
Queue_1.swap(Queue_2);
cout<<"Element in Queue_1 are: ";
while (!Queue_1.empty()){
cout << ' ' << Queue_1.front();
Queue_1.pop();
}
cout<<"\nElement in Queue_2 are: ";
while (!Queue_2.empty()){
cout << ' ' << Queue_2.front();
Queue_2.pop();
}
}輸出
如果我們執行以上程式碼,它會生成以下輸出 -
Element in Queue_1 are: 5 6 7 8 9 10 Element in Queue_1 are: 0 1 2 3 4 5
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式
C++
C#
MongoDB
MySQL
Javascript
PHP