tags:

views:

284

answers:

4

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

+7  A: 

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).

Andrew Hare
This seems like the slow way to do it, since max_element can't know that the range is sorted.
Mark Ransom
This is what I get for answering a question outside my comfort zone :) I didn't know that an `std::set` was sorted by default. Since I assumed that it was not sorted an O(n) algorithm seemed to be the only practical choice. Now knowing what I know, yes this answer is not optimal.
Andrew Hare
+16  A: 

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.

CTT
Unless of course the set is empty.
Mark Ransom
Finding the max element is constant time, yes, but populating the set is not, since it's sorting at insert. A unordered_set has constant time insert, but would require a search for the maximum element.
crunchdog
But since the original question starts with "I have a std::set", we can assume that non-constant insertion time is going to be incurred regardless of our searching mechanism. Since you've already paid the price, why not take advantage of it by using a constant-time search method?
Darryl
+15  A: 

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

Darryl
+4  A: 

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

Naveen