雙端隊列或雙端隊列是序列容器,兩端都有擴展和收縮函數。它們類似於向量,但是在元素的結尾和開始處插入和刪除時效率更高。與向量不同,可能無法保證連續的存儲分配。
deque::at()
at()函數用於參考在作為函數參數給出的位置上存在的元素。句法:
dequename.at(position) 參數: Position of the element to be fetched. 返回: Direct reference to the element at the given position.
例子:
Input : mydeque = 1, 2, 3 mydeque.at(2); Output: 3 Input : mydeque = 3, 4, 1, 7, 3 mydeque.at(3); Output: 7
錯誤和異常
1.如果雙端隊列中不存在該位置,則拋出out_of_range。 2.否則,它具有強大的無異常拋出保證。
// CPP program to illustrate
// Implementation of at() function
#include <deque>
#include <iostream>
using namespace std;
int main()
{
deque<int> mydeque;
mydeque.push_back(3);
mydeque.push_back(4);
mydeque.push_back(1);
mydeque.push_back(7);
mydeque.push_back(3);
cout << mydeque.at(3);
return 0;
}
輸出:
7
應用
給定整數雙端隊列,請打印出現在偶數位置的所有整數。
Input :1, 2, 3, 4, 5, 6, 7, 8, 9 Output:1 3 5 7 9 Explanation - 1, 3, 5, 7 and 9 are at position 0, 2, 4, 6 and 8 which are even
算法
1.循環運行直至達到陣列大小。
2.檢查該位置是否可被2整除,如果是,則在該位置打印元素。
// CPP program to illustrate
// Application of at() function
#include <deque>
#include <iostream>
using namespace std;
int main()
{
deque<int> mydeque;
mydeque.push_back(1);
mydeque.push_back(2);
mydeque.push_back(3);
mydeque.push_back(4);
mydeque.push_back(5);
mydeque.push_back(6);
mydeque.push_back(7);
mydeque.push_back(8);
mydeque.push_back(9);
// Deque becomes 1, 2, 3, 4, 5, 6, 7, 8, 9
for (int i = 0; i < mydeque.size(); ++i) {
if (i % 2 == 0) {
cout << mydeque.at(i);
cout << " ";
}
}
return 0;
}
輸出:
1 3 5 7 9
deque::swap()
此函數用於將一個雙端隊列的內容與相同類型和大小的另一個雙端隊列交換。
用法:
dequename1.swap(dequename2) 參數: The name of the deque with which the contents have to be swapped. Result: All the elements of the 2 deque are swapped.
例子:
Input :mydeque1 = {1, 2, 3, 4} mydeque2 = {3, 5, 7, 9} mydeque1.swap(mydeque2); Output:mydeque1 = {3, 5, 7, 9} mydeque2 = {1, 2, 3, 4} Input :mydeque1 = {1, 3, 5, 7} mydeque2 = {2, 4, 6, 8} mydeque1.swap(mydeque2); Output:mydeque1 = {2, 4, 6, 8} mydeque2 = {1, 3, 5, 7}
錯誤和異常
1.如果雙端隊列的類型不同,則會引發錯誤。
2.如果雙端隊列大小不同,則會引發錯誤。
2.它具有基本的無異常拋出保證。
// CPP program to illustrate
// Implementation of swap() function
#include <deque>
#include <iostream>
using namespace std;
int main()
{
// deque container declaration
deque<int> mydeque1{ 1, 2, 3, 4 };
deque<int> mydeque2{ 3, 5, 7, 9 };
// using swap() function to swap elements of deques
mydeque1.swap(mydeque2);
// printing the first deque
cout << "mydeque1 = ";
for (auto it = mydeque1.begin(); it < mydeque1.end(); ++it)
cout << *it << " ";
// printing the second deque
cout << endl
<< "mydeque2 = ";
for (auto it = mydeque2.begin(); it < mydeque2.end(); ++it)
cout << *it << " ";
return 0;
}
輸出:
mydeque1 = 3 5 7 9 mydeque2 = 1 2 3 4
相關用法
注:本文由純淨天空篩選整理自AyushSaxena大神的英文原創作品 deque::at() and deque::swap() in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。