How do I find the largest int in a std::set<int>?

C++StlStdset

C++ Problem Overview


I have a std::set<int>, what's the proper way to find the largest int in this set?

C++ Solutions


Solution 1 - C++

What comparator are you using?

For the default this will work:

if(!myset.empty())
    *myset.rbegin();
else
    //the set is empty

This will also be constant time instead of linear like the max_element solution.

Solution 2 - C++

Sets are always ordered. Assuming you are using the default comparison (less), just grab the last element in the set. rbegin() might be useful.

Solution 3 - C++

I believe you are looking for std::max_element:

> The max_element() function returns an > iterator to the largest element in the > range [start,end).

Solution 4 - C++

Since set sorts the element in ascending order by default, just pick up the last element in the set.

Solution 5 - C++

if(!myset.empty())
    *myset.rend();
else
    //the set is empty

In an ordered integer set, the last element is the largest one.

Solution 6 - C++

Before you push() in your set<int> save the value in int max in global variable

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleeeroyView Question on Stackoverflow
Solution 1 - C++CTTView Answer on Stackoverflow
Solution 2 - C++DarrylView Answer on Stackoverflow
Solution 3 - C++Andrew HareView Answer on Stackoverflow
Solution 4 - C++NaveenView Answer on Stackoverflow
Solution 5 - C++Baris UlgenView Answer on Stackoverflow
Solution 6 - C++arafat almubarokView Answer on Stackoverflow