Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
How to Find All Occurrences of an Element in a List in C++?
Next article icon

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

Last Updated : 16 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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; } 

Output
The 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)


Next Article
How to Find All Occurrences of an Element in a List in C++?

R

rohitpant4532
Improve
Article Tags :
  • C++ Programs
  • C++
  • STL
  • cpp-list
  • CPP Examples
Practice Tags :
  • CPP
  • STL

Similar Reads

  • How to Find All Occurrences of an Element in a List in C++?
    In C++, std::list is a sequence container that allows non-contiguous memory allocation. As such, it is a doubly linked list that can be traversed in both directions. In this article, we will learn how to find all occurrences of a specific element in a list in C++. Example: Input: myList = {7, 5, 16,
    2 min read
  • How to Find First Occurrence of an Element in a List in C++?
    In C++, the list is a sequence container that stores data in non-contiguous memory allocation. It is defined in the STL (Standard Template Library) inside the <list> header. In this article, we will learn how to find the first occurrence of a specific element in a list in C++. Example: Input:
    3 min read
  • How to Find Last Occurrence of an Element in a Deque in C++?
    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,
    2 min read
  • How to Find All Occurrences of an Element in a Multiset in C++?
    In C++, a multiset is a container similar to a set but it allows multiple occurrences of its elements i.e. duplicate values. In this article, we will learn how to find all occurrences of a specific element in a multiset in C++. Example: Input: myMultiset = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};target = 3Ou
    2 min read
  • How to Find the Last Occurrence of an Element in a Set in C++?
    In C++, a set is a container that stores unique elements in a sorted order and elements are accessed and traversed using iterators. In this article, we will learn how to find the last occurrence of a specific element in a set in C++. Example Input:set<int> s = {1, 2, 3, 4, 5, 6, 7, 8, 9}; Key
    2 min read
  • How to Find All Occurrences of an Element in a Set in C++?
    Finding the all occurrences of a specific element in a set using the C++ STL is a very efficient process that is done with the help of std::set::distance() member function. In this article, we'll explore how to find the first element in a set using the C++ STL. For Example,Input:mySet = {1, 2, 4, 3,
    2 min read
  • How to Find Last Occurrence of an Element in Vector?
    In C++, the last occurrence of an element in a vector means the last time that element appeared in the vector if traversed from the start. In this article, we will learn how to find the last occurrence of a specific element in a vector in C++. Example Input:vector<int> vec= {2, 5, 9, 8, 5, 4,
    2 min read
  • How to Find First Occurrence of an Element in a Set in C++?
    In C++, a set is an ordered container that stores its unique values in some given order. In this article, we will see how to find the first occurrence of a specific element in a set in C++ STL. For Example, Input: mySet = {1, 2, 3, 8, 9, 11} Target = 9 Output: Element found at Index: 4Find the First
    2 min read
  • 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: Th
    2 min read
  • How to Find All Occurrences of an Element in a Deque in C++?
    In C++, deques are data structures similar to queues provided by the STL library in C++ but unlike queues, deques allow the insertion and deletion of elements from both ends. In this article, we will learn how to find all occurrences of a specific element in a deque in C++. Example Input: deque<i
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences