deque assign() function in C++ STL

C++Server Side ProgrammingProgramming

Given the task is to show the working of deque::assign() in C++ STL.

Deque is a double ended queue. In C++, deque::assign() is an inbuilt function which is used to assign the new value to the deque container. Every time this function is called it assigns a new value to the deque container by replacing the existing values and changing the size allocated accordingly.

Syntax

Syntax of deque::assign() is as follows −

dequename.assign(<int> size, <int> val)

Parameters

This function includes 2 parameters −

First is the size, which represents the size of the deque container and the second one is val, which is the value contained by the deque container.

Also instead of size and val we can also give iterator as parameter to declare the starting and ending point, the depiction of both is given as an example.

Return value

The function has no return value.

Example

Input: dq.assign(5, 1)
Output: deque elements are: 1 1 1 1 1
Input: dq.assign(5, 2)
dq1.assign(dq.start()+2, dq.end())
Output: deque elements are: 2 2 2 2 2
deque elements are: 2 2 2

Explanation − deque dq has 5 elements 2 2 2 2 2, whereas in dq1 we are skipping 2 elements from the start and starting from the third element of dq so dq1 has 2 2 2.

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
deque<int> deq;
// assign 5 values of 1 each
deq.assign(5, 1); //here, 5 is the size and 1 is the value
cout << "deque elements are: ";
for (auto it = deq.begin(); it != deq.end(); it++)
cout << *it << " ";
return 0;
}

Output

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

deque elements are: 1 1 1 1 1

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
deque<int> deq;
// assign 5 values of 2 each
deq.assign(5, 2);
cout << "deque elements are: ";
for (auto it = deq.begin(); it != deq.end(); it++)
cout << *it << " ";
deque<int> deq1;
// assigns all elements from
// the second position to deque1
deq1.assign(deq.begin() + 2, deq.end());
cout << "\ndeque1 elements are: ";
for (auto it = deq1.begin(); it != deq1.end(); it++)
cout << *it << " ";
return 0;
}

Output

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

deque elements are: 2 2 2 2 2
deque1 elements are: 2 2 2
Published on 20-Jan-2020 07:14:55