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

C++Server Side ProgrammingProgramming

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
adeque.at(3);
Output : 5
Input : adeque = 1, 3, 5, 7,9
adeque.at(2);
Output : 5

Example

 Live Demo

#include <deque>
#include <iostream>
using namespace std;
int main(){
   deque<int> adeque;
   adeque.push_back(1);
   adeque.push_back(3);
   adeque.push_back(4);
   adeque.push_back(5);
   adeque.push_back(8);
   cout << adeque.at(3);
   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}
adeque.swap(bdeque);
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
   adeque.swap(bdeque);
   // code for printing the elemets of adeque
   cout << "adeque = ";
   for (auto it = adeque.begin(); it < adeque.end(); ++it)
      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}
raja
Published on 02-Mar-2020 14:01:43
Advertisements