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

為{幸葍}努か 提交于 2019-12-03 08:04:05

问题


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


回答1:


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.




回答2:


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




回答3:


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




回答4:


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




回答5:


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



来源:https://stackoverflow.com/questions/1342045/how-do-i-find-the-largest-int-in-a-stdsetint

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!