Open In App

How to Create Deque of User-Defined Data Type in C++?

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, deque is a container in which we can insert and delete at both its beginning and its end. It supports almost all kinds of inbuilt data types. In this article, we will learn how to create a deque of user-defined data types in C++.

Example

Input:
//user defined data type
struct usd {
int a;
char b;
};

Output:
Elements in the Stack of usd:
(1, 'c')
(1, 'd')

Create a Deque of User-Defined Data Type in C++

If our user defined data type is copy constructible and assignable, we can create a std::deque of user-defined data type by passing that type as the template parameter in the deque declaration.

Syntax:

deque<DataType> dq_Name;

C++ Program to Create a Deque of User-Defined Data Type

The following program illustrates how we can create a deque of user-defined data type in C++:

C++
// C++ program to illustrate how to create a deque of
// user-defined data type
#include <deque>
#include <iostream>
#include <string>
using namespace std;

// Define the user-defined data type
class Person {
public:
    string name;
    int age;

    Person(string name, int age)
    {
        this->name = name;
        this->age = age;
    }
};

int main()
{
    // Creating a deque of user-defined data type
    deque<Person> dq;

    // Create Person objects
    Person p1("John", 30);
    Person p2("Steve", 40);
    Person p3("David", 50);
    Person p4("Alice", 60);

    // Insert the Person objects to the deque
    dq.push_back(p1);
    dq.push_back(p2);
    dq.push_back(p3);
    dq.push_back(p4);

    // Print the deque elements
    cout << " Deque Elements: " << endl;
    for (Person& p : dq) {
        cout << "{ Name: " << p.name << ", Age: " << p.age
             << " }" << endl;
    }

    return 0;
}

Output
 Deque Elements: 
{ Name: John, Age: 30 }
{ Name: Steve, Age: 40 }
{ Name: David, Age: 50 }
{ Name: Alice, Age: 60 }

Time Complexity: O(N) where N is the number of elements in the deque.
Auxiliary Space: O(N)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads