Open In App

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

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, deques also known as double-ended queues are sequence containers that allow the users to insert and delete elements from both ends efficiently. In this article, we will learn how to find the last occurrence of a specific element in a deque in C++.

Example

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

Output:
Last occurrence of element 2 found at index 8

Finding the Last Occurrence of a Specific Element in a Deque in C++

To find the last occurrence of a specific element in a std::deque, we can use the std::find() method with the reverse iterator to the deque. The find() function returns the iterator to the first matching element. By using reverse iterators, we can find the last occurrence instead of the first one.

Syntax of find()

std::find(first, last, target)

Here,

  • first:Iterator to the beginning of the range.
  • last: Iterator to the end of the range.

C++ Program to Find Last Occurrence of an Element in a Deque

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

C++
// C++ Program to demonstrate how we can find the last
// 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 = { 1, 2, 3, 4, 2, 5, 2, 6, 2 };

    // Declare the target element whose last occurrence is
    // required
    int target = 2;

    // Find the last occurrence of the target element
    auto it = find(dq.rbegin(), dq.rend(), target);

    if (it != dq.rend()) {
        // Calculating the index of the last occurrence
        // correctly
        cout << "Last occurrence of " << target
             << " found at index: " << dq.rend() - it - 1
             << endl;
    }
    else {
        cout << "Element not found in the deque." << endl;
    }

    return 0;
}

Output
Last occurrence of 2 found at index: 8

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




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads