Open In App

Difference Between deque::assign and deque::empty in C++

Last Updated : 17 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Deque or Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in the case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed.

 Here we will see the difference between deque::assign and deque::at in C++.

deque::assign

deque::assign is used to assign new contents to the deque container by replacing its current contents. It changes its size accordingly.

Syntax:

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

Parameters:

  1. size – Number of values to be assigned to the container.
  2. val – Value to be assigned to the container.

Header File:

<deque>

Exceptions: If an exception is thrown, the container is in a valid state.

Iterator Validity: In this container, all the iterators, pointers, and references are invalidated.

Example:

C++




// C++ program to implement deque::assign
#include <deque>
#include <iostream>
using namespace std;
 
int main()
{
    // Declaration of Deque
    deque<int> d1 = { 1, 3, 6, 0, 0 };
    deque<int> d2;
 
    // Assigning d1 deque elements
    // into d2 deque
    d2.assign(d1.begin(), d1.end());
 
    cout << "Elements in d2 container are : ";
    for (auto it = d2.begin(); it != d2.end(); ++it) {
        cout << *it << " ";
    }
    cout << endl;
    return 0;
}


Output

Elements in d2 container are : 1 3 6 0 0 
  • Time Complexity – O(N)
  • Space Complexity – O(N)

deque::empty 

deque::empty is used to check whether the deque container is empty or not. It does not change anything in the container.

Syntax:

empty();

Header File:

<deque>

Exceptions: It never throws any exception

Iterator Validity: Iterator Validity does not change in this container.

Example:

C++




// C++ program to implement deque::empty
#include <deque>
#include <iostream>
using namespace std;
 
int main()
{
    // Declaration of Deque
    deque<int> GFG = { 1, 3, 6, 0, 0 };
 
    if (GFG.empty() == true) {
        cout << "The deque is empty" << endl;
    }
    else {
        cout << "The deque is not empty" << endl;
    }
    return 0;
}


Output

The deque is not empty
  • Time Complexity – O(1)
  • Space Complexity – O(1)

Differences between deque::assign and deque::empty 

Basis

deque::assign

deque::empty

Definition It is used to assign new contents to the deque container. It is used to check whether a deque is empty or not.
Syntax dequename.assign(<int> size, <int> val); empty()
Number of Parameters It takes only two parameters None
Return Value None Boolean
Complexity Linear Constant


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads