Open In App

How to Find First Occurrence of an Element in a Deque in C++?

In C++, deques also known as double-ended queues are sequence containers with the feature of insertion and deletion on both ends. In this article, we will learn how to find the first occurrence of a specific element in a deque in C++.

Example

Input:
myDeque ={2, 1, 5, 3, 4, 2, 5}
Target=5

Output:
The first occurrence of element 5 is at index 2.

Find the First Occurrence of an Element in a Deque in C++

To find the first occurrence of a specific element in a std::deque in C++, we can use the std::find method that returns an iterator pointing to the first occurrence of a specific element. We can then subtract the value of the begin iterator from the iterator returned by the find method to get the index of the first occurrence of the target element.

Syntax to Use std::find()

find(dq.begin(), dq.end(), target)

Here,

C++ Program to Find the First Occurence of a Specific Element in a Deque

The following program illustrates how we can find the first occurrence of a specific element in a deque in C++.

// C++ Program to illustrate how we can find the first
// occurrence of a specific element in a deque
#include <algorithm>
#include <deque>
#include <iostream>
using namespace std;

int main()
{
    // Initialize a deque
    deque<int> dq = { 2, 1, 5, 3, 4, 2, 5 };

    // Delcare the element whose first occurence is required
    int target = 5;

    // Find the first occurrence of the target element using
    // find
    auto it = find(dq.begin(), dq.end(), target);

    // Print the first occurence of the target element
    if (it != dq.end()) {
    std:
        cout << "The first occurence of element: " << target
             << " is at index: " << (it - dq.begin())
             << endl;
    }
    else {
        cout << "Element not found" << endl;
    }

    return 0;
}

Output
The first occurence of element: 5 is at index: 2

Time Complexity: O(N), where N is the size of the deque.
Auxiliary Space: O(1)



Article Tags :