Reputation: 11446
I have a std::set<int>
, what's the proper way to find the largest int in this set?
Upvotes: 72
Views: 55041
Reputation: 19
if(!myset.empty())
*myset.rend();
else
//the set is empty
In an ordered integer set, the last element is the largest one.
Upvotes: 0
Reputation: 1
Before you push()
in your set<int>
save the value in int max
in global variable
Upvotes: -5
Reputation: 17631
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.
Upvotes: 127
Reputation: 73443
Since set sorts the element in ascending order by default, just pick up the last element in the set.
Upvotes: 5
Reputation: 6217
Sets are always ordered. Assuming you are using the default comparison (less), just grab the last element in the set. rbegin() might be useful.
Upvotes: 34
Reputation: 351536
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).
Upvotes: 6