C++ 如何在 std::set<int> 中找到最大的 int?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1342045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I find the largest int in a std::set<int>?
提问by leeeroy
I have a std::set<int>
, what's the proper way to find the largest int in this set?
我有一个std::set<int>
,在这个集合中找到最大整数的正确方法是什么?
回答by CTT
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.
这也将是恒定时间,而不是像 max_element 解决方案那样线性。
回答by Darryl
Sets are always ordered. Assuming you are using the default comparison (less), just grab the last element in the set. rbegin() might be useful.
集合总是有序的。假设您使用的是默认比较(较少),只需获取集合中的最后一个元素。rbegin() 可能有用。
回答by Naveen
Since set sorts the element in ascending order by default, just pick up the last element in the set.
由于 set 默认按升序对元素进行排序,因此只需选取 set 中的最后一个元素即可。
回答by Andrew Hare
I believe you are looking for std::max_element
:
我相信你正在寻找std::max_element
:
The
max_element()
function returns an iterator to the largest element in the range [start,end).
该
max_element()
函数返回一个迭代器,指向范围 [start,end) 中的最大元素。
回答by arafat almubarok
Before you push()
in your set<int>
save the value in int max
in global variable
你之前push()
在你set<int>
保存的值int max
在全局变量