How to Find the Last Element in a Set in C++?
Last Updated :
27 Feb, 2024
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++
#include <iostream>
#include <set>
using namespace std;
int main()
{
set< int > mySet = { 5, 2, 8, 1, 4 };
int lastElement = *mySet.rbegin();
cout << "Last element is: " << lastElement << endl;
return 0;
}
|
Output
Last element is: 8
Time complexity :O(1)
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...