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

后端 未结 5 1520
深忆病人
深忆病人 2021-02-03 17:19

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

相关标签:
5条回答
  • 2021-02-03 17:29

    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.

    0 讨论(0)
  • 2021-02-03 17:29

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

    0 讨论(0)
  • 2021-02-03 17:32

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

    0 讨论(0)
  • 2021-02-03 17:36

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

    0 讨论(0)
  • 2021-02-03 17:41

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

    0 讨论(0)
提交回复
热议问题