双端队列或双端队列是序列容器,两端都有扩展和收缩功能。它们与向量类似,但是在元素的结尾和开始处插入和删除时效率更高。与向量不同,可能无法保证连续的存储分配。
deque :: at()
at()函数用于引用作为函数参数给出的位置处的元素。
句法 :
dequename.at(position)
Parameters :
Position of the element to be fetched.
Returns :
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
#include
using namespace std;
int main()
{
deque 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
#include
using namespace std;
int main()
{
deque 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)
Parameters :
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
#include
using namespace std;
int main()
{
// deque container declaration
deque mydeque1{ 1, 2, 3, 4 };
deque 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
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。