C++ <deque> - operator=() Function
The C++ deque::operator= function is used to assign new content to the container by replacing the current content and adjusting the container size accordingly.
Syntax
//copies all elements of x into the container deque& operator= (const deque& x);
//copy version - copies all elements //of x into the container deque& operator= (const deque& x); //move version - moves elements of x //into the container deque& operator= (deque&& x); //initializer list version - copies all //elements of il into the container deque& operator= (initializer_list<value_type> il);
Parameters
x |
Specify a deque object of same type. |
il |
Specify an initializer_list object. |
Return Value
Returns *this.
Time Complexity
Linear i.e, Θ(n).
Example: using copy version
In the example below, the deque::operator= function is used to assign new values to the given deque.
#include <iostream> #include <deque> using namespace std; int main (){ deque<int> dq1{10, 20, 30, 40, 50}; //copying all content of dq1 into dq2 deque<int> dq2; dq2 = dq1; cout<<"The dq1 contains:"; for(int i = 0; i < dq1.size(); i++) cout<<" "<<dq1[i]; cout<<"\nThe dq2 contains:"; for(int i = 0; i < dq2.size(); i++) cout<<" "<<dq2[i]; return 0; }
The output of the above code will be:
The dq1 contains: 10 20 30 40 50 The dq2 contains: 10 20 30 40 50
Example: using move version
Using the move version of operator=, the content of one deque can be moved to another deque. Consider the following example:
#include <iostream> #include <deque> using namespace std; int main (){ deque<int> dq1{10, 20, 30, 40, 50}; cout<<"The dq1 contains:"; for(int i = 0; i < dq1.size(); i++) cout<<" "<<dq1[i]; //moving all content of dq1 into dq2 deque<int> dq2; dq2 = move(dq1); cout<<"\nThe dq1 contains:"; for(int i = 0; i < dq1.size(); i++) cout<<" "<<dq1[i]; cout<<"\nThe dq2 contains:"; for(int i = 0; i < dq2.size(); i++) cout<<" "<<dq2[i]; return 0; }
The output of the above code will be:
The dq1 contains: 10 20 30 40 50 The dq1 contains: The dq2 contains: 10 20 30 40 50
Example: using initializer list version
The initializer list can also be used to assign values into a deque container. Consider the example below:
#include <iostream> #include <deque> using namespace std; int main (){ //creating empty deque deque<int> dq; //creating initializer list initializer_list<int> ilist = {10, 20, 30, 40, 50}; //assigning values of dq using ilist dq = ilist; cout<<"The dq contains:"; for(int i = 0; i < dq.size(); i++) cout<<" "<<dq[i]; return 0; }
The output of the above code will be:
The dq contains: 10 20 30 40 50
❮ C++ <deque> Library