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

2019-03-11 13:51发布

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

标签: c++ stl stdset
5条回答
▲ chillily
2楼-- · 2019-03-11 14:04

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.

查看更多
▲ chillily
3楼-- · 2019-03-11 14:05

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

查看更多
Summer. ? 凉城
4楼-- · 2019-03-11 14:17

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

查看更多
我命由我不由天
5楼-- · 2019-03-11 14:22

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

查看更多
SAY GOODBYE
6楼-- · 2019-03-11 14:24

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

查看更多
登录 后发表回答