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.
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.
at() function is used to provide reference to the element present at a particular position given as the parameter to the function.
dequename.at(position of element)
Position of the element
Direct reference to the element at the given position.
Input : adeque = 1, 3, 4, 5, 8 adeque.at(3); Output : 5 Input : adeque = 1, 3, 5, 7,9 adeque.at(2); Output : 5
#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; }
If we run the above code it will generate the following output −
5
swap() function is used to interchange or swap the elements of two deque’s of same type and same size.
Deque1name.swap(deque2name)
Parameters contains the name of the deque with which the contents of deque1 have to be shaped.
All the elements of both the deque are interchanged or swapped.
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}
#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; }
If we run the above code it will generate the following output
adeque = {2, 6, 7, 9, 0} bdeque = {1, 3, 4, 5, 8}