優先級隊列是一種容器適配器,經過專門設計,使得隊列的第一個元素在隊列中的所有元素中占最大。
priority_queue::swap()
此函數用於將一個優先級隊列的內容與相同類型和大小的另一個優先級隊列交換。
用法:
priorityqueuename1.swap(priorityqueuename2) 參數: The name of the priority queue with which the contents have to be swapped. Result: All the elements of the 2 priority queues are swapped.
例子:
Input :mypqueue1 = {1, 2, 3, 4} mypqueue2 = {3, 5, 7, 9} mypqueue1.swap(mypqueue2); Output:mypqueue1 = {9, 7, 5, 3} mypqueue2 = {4, 3, 2, 1} Input :mypqueue1 = {1, 3, 5, 7} mypqueue2 = {2, 4, 6, 8} mypqueue1.swap(mypqueue2); Output:mypqueue1 = {8, 6, 4, 2} mypqueue2 = {7, 5, 3, 1}
Note: In priority_queue container, the elements are printed in reverse order because the top is printed first then moving on to other elements.
錯誤和異常
1.如果優先級隊列的類型不同,則會引發錯誤。
2.它具有基本的無異常拋出保證。
// CPP program to illustrate
// Implementation of swap() function
#include <iostream>
#include <queue>
using namespace std;
int main()
{
// priority_queue container declaration
priority_queue<int> mypqueue1;
priority_queue<int> mypqueue2;
// pushing elements into the 1st priority queue
mypqueue1.push(1);
mypqueue1.push(2);
mypqueue1.push(3);
mypqueue1.push(4);
// pushing elements into the 2nd priority queue
mypqueue2.push(3);
mypqueue2.push(5);
mypqueue2.push(7);
mypqueue2.push(9);
// using swap() function to swap elements of priority queues
mypqueue1.swap(mypqueue2);
// printing the first priority queue
cout << "mypqueue1 = ";
while (!mypqueue1.empty()) {
cout << mypqueue1.top() << " ";
mypqueue1.pop();
}
// printing the second priority queue
cout << endl
<< "mypqueue2 = ";
while (!mypqueue2.empty()) {
cout << mypqueue2.top() << " ";
mypqueue2.pop();
}
return 0;
}
輸出:
mypqueue1 = 9 7 5 3 mypqueue2 = 4 3 2 1
相關用法
注:本文由純淨天空篩選整理自AyushSaxena大神的英文原創作品 priority_queue::swap() in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。