deque::at() and deque::swap() in C++ STL

In this article we are going to discuss the deque::at() and deque::swap() function in C++ STL function syntax, working and its return values.

What is deque::at() and deque::swap() function in STL?

Deque or Double ended queues are as name suggests, sequence containers which can be expanded or contracted at both the ends. The user can easily insert data from any of the ends and similarly delete data from any of the ends. They are similar to vectors, but the only difference is that unlike vectors, contiguous storage allocation may not be guaranteed. Still Deque is more efficient in case of insertion and deletion of elements at both the ends.

deque::at()

at() function is used to provide reference to the element present at a particular position given as the parameter to the function.

Syntax

dequename.at(position of element)

Parameter

Position of the element

Return Value

Direct reference to the element at the given position.

Examples

Input : adeque = 1, 3, 4, 5, 8
Output : 5
Input : adeque = 1, 3, 5, 7,9
Output : 5

Example

Live Demo

#include <deque>
#include <iostream>
using namespace std;
int main(){
return 0;
}

Output

If we run the above code it will generate the following output −

5

deque::swap()

swap() function is used to interchange or swap the elements of two deque’s of same type and same size.

Syntax

Deque1name.swap(deque2name)

Parameter

Parameters contains the name of the deque with which the contents of deque1 have to be shaped.

Return Value

All the elements of both the deque are interchanged or swapped.

Examples

Input : adeque = {1, 3, 4, 5, 8}
bdeque = {2, 6, 7, 9, 0}
Output : adeque = {2, 6, 7, 9, 0}
bdeque = {1, 3, 4, 5, 8}

Example

Live Demo

#include <deque>
#include <iostream>
using namespace std;
int main(){
// deque container declaration
deque<int> adeque{ 1, 2, 3, 4 };
deque<int> bdeque{ 3, 5, 7, 9 };
// using swap() function to swap elements of deques
// code for printing the elemets of adeque
cout << *it << " ";
// code for printing the elemets of bdeque
cout << endl
<< "bdeque = ";
for (auto it = bdeque.begin(); it < bdeque.end(); ++it)
cout << *it << " ";
return 0;
}

Output

If we run the above code it will generate the following output

adeque = {2, 6, 7, 9, 0}
bdeque = {1, 3, 4, 5, 8}