How to Find Last Occurrence of an Element in a List in C++?
Last Updated :
16 Apr, 2024
In C++, std::list represents a doubly linked list and the last occurrence of an element in a list refers to the last time that element appears in the list when traversed from the beginning. In this article, we will learn how to find the last occurrence of a specific element in a list in C++.
Example:
Input:
list<int>
myList = {1, 2, 7, 4, 5, 7, 8}
int key = 7;
Output:
The last occurrence of element 7 is found at index : 5
Find the Last Occurrence of an Element in a List in C++
To find the last occurrence of an element in a std::list
, we can use the std::find()
function with reverse iterators std::list::rbegin()
and std::list::rend()
to iterate through the list in reverse order. When we iterate in reverse order, the first occurrence is the last occurrence of that element.
Approach
- Use the std::find function along with reverse iterators to get the iterator pointing to the first occurrence of the target element from the last.
- If the element is found calculate its index using the std::distance function. Pass the base iterator (which points to one position past the end of the list in a forward direction) and the begin iterator to this function.
- Since list indexing is zero-based, subtract one from the result obtained from the
std::distance
function to get the correct index. - Finally, print the index which denotes the last occurrence of the specific element in the list.
C++ Program to Find the Last Occurrence of an Element in a List
The below example demonstrates how to find the last occurrence of a specific element in a given list in C++.
C++
// C++ program to demonstrate how to find the last
// occurrence of a specific element in a given list
#include <algorithm>
#include <iostream>
#include <list>
using namespace std;
int main()
{
// Initializing a list of integers
list<int> myList = { 1, 2, 7, 4, 5, 7, 8 };
// Declare the element whose last occurrence is to be
// found
int element = 7;
// Finding the last occurrence of the element
auto it = find(myList.rbegin(), myList.rend(), element);
// Printing the position of the last occurrence of the
// element
if (it != myList.rend()) {
// Finding the index of the last occurrence of the
// element
int position
= distance(myList.begin(), it.base()) - 1;
cout << "The last occurrence of element " << element
<< " is found at index : " << position << endl;
}
else {
cout << "Element not found in the list" << endl;
}
return 0;
}
OutputThe last occurrence of element 7 is found at index : 5
Time Complexity: O(n), here n is the number of elements in the list.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...