C++ Deque::assign() Function



The C++ std::deque::assign() function is used to replace the elements of deque with new elemenets. It is used for managing and updating the deque data, ensuring it holds the desired elements in a specified position. This function has 3 polymorphic variants: with using the range version, fill version and the initializer list version (you can find the syntaxes of all the variants below).

Syntax

Following is the syntax for std::deque::assign() function.

void assign (InputIterator first, InputIterator last);
or
void assign (size_type n, const value_type& val);
or
void assign (initializer_list<value_type> il);

Parameters

  • first, last − It indicates the input iterators to the initial and final positions in sequence.
  • n − It indicates the new size for the container.
  • val − It indicates the value to fill the container.
  • il − It indicates an initializer list object.

Return value

This function does not return anything.

Exceptions

This function return undefined if the specified of first and last is not valid.

Time complexity

The time complexity of this function is Linear i.e. O(n)

Example

Let's look at the following example, where we are going to assign the elements from the initializer list.

#include <iostream>
#include <deque>
int main()
{
    std::deque<char> a;
    a.assign({'A', 'B', 'C', 'D'});
    for (auto& elem : a) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

A B C D 

Example

Consider the following example, where we are going to assign the range of elements.

#include <iostream>
#include <deque>
int main()
{
    std::deque<int> x;
    std::deque<int> y = {1, 22, 333, 4444};
    x.assign(y.begin(), y.end());
    for (auto& elem : x) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;
    return 0;
}

Output

Following is the output of the above code −

1 22 333 4444 

Example

In the following example, we are going to assign the 3 elements with value 11.

#include <iostream>
#include <deque>
int main()
{
    std::deque<int> a;
    a.assign(3, 11);
    for (auto& elem : a) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;
    return 0;
}

Output

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

11 11 11 
deque.htm
Advertisements