Horje
How to Find the Last Element in a Set in C++?

In C++, sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending. In this article, we will learn how to find the last element in a set in C++.

Example:

Input:
mySet = {1, 2, 3, 4, 5}

Output: 5

Finding the Last Element in a Set in C++

To find the last element in a std::set in C++, we can use the std::set::rbegin() function that returns a reverse iterator pointing to the last element of the set. We can then dereference this iterator to find the last element.

C++ Program to Find the Last Element in a Set

C++

// C++ Program to find the last element in a Set
#include <iostream>
#include <set>
using namespace std;
  
int main()
{
    // Set declaration
    set<int> mySet = { 5, 2, 8, 1, 4 };
  
    // Finding the last element
    int lastElement = *mySet.rbegin();
  
    // Printing the last element
    cout << "Last element is: " << lastElement << endl;
  
    return 0;
}

Output

Last element is: 8


Time complexity :O(1)
Space Complexity: O(1)




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Use Iterator with a Vector in C++? How to Use Iterator with a Vector in C++?
How to Add an Element to a Set in C++? How to Add an Element to a Set in C++?
How to Delete an Element from a Set in C++? How to Delete an Element from a Set in C++?
How to Replace an Element in a Vector in C++? How to Replace an Element in a Vector in C++?
How to Find the Sum of Elements in an Array in C++? How to Find the Sum of Elements in an Array in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13