美文网首页
C++算法库——最小/最大操作(max, max_element

C++算法库——最小/最大操作(max, max_element

作者: 霜天渔火 | 来源:发表于2019-07-27 18:03 被阅读0次
  • 头文件<algorithm>

max:返回各给定值中的较大者

  • 相关函数:
    • min
    • minmax:返回pair;若有多个,最小取最左的,最大取最右的

返回a与b的较大者

  • 返回a或b的引用

  • 默认用operator<比较

template< class T > 
constexpr const T& max( const T& a, const T& b );
  • 或者自定义比较函数bool cmp(const Type1 &a, const Type2 &b);
template< class T, class Compare >
constexpr const T& max( const T& a, const T& b, Compare cmp );
  • 关于比较函数:
    • 传入参数必须有const
    • T类型必须能隐式转换为Type1Type2
    • 若a < b,则返回true

返回初始化列表中值的最大者

  • 返回T类型的值

  • 声明:

template< class T >
constexpr T max( std::initializer_list<T> ilist );
template< class T, class Compare >
constexpr T max( std::initializer_list<T> ilist, Compare comp );
  • 举例:
const string str = max( { "foo", "bar", "hello" },
    [](const string& s1, const string& s2) {
        return s1.size() < s2.size();
    });

max_element:返回范围内的最大元素

  • 相关函数:

    • min_element
    • minmax_element:返回pair;若有多个,最小取最左的,最大取最右的
  • 声明:

template< class ForwardIt > 
constexpr ForwardIt max_element(ForwardIt first, ForwardIt last );
template< class ForwardIt, class Compare >
constexpr ForwardIt max_element(ForwardIt first, ForwardIt last, Compare comp );
  • 举例:
vector<int> v{ 1, 2, 3 };
int result = *max_element( v.begin(), b.end() );
  • 返回迭代器
    • 若有多个最大值,返回首个迭代器
    • 若范围为空,返回last

clamp:裁剪到给定范围

  • 声明:
template<class T>
constexpr const T& clamp( const T& v, const T& lo, const T& hi );
template<class T, class Compare>
constexpr const T& clamp( const T& v, const T& lo, const T& hi, Compare comp );
  • 入参与返回值都是引用
    • 如果vlohi相等,返回v的引用

相关文章

网友评论

      本文标题:C++算法库——最小/最大操作(max, max_element

      本文链接:https://www.haomeiwen.com/subject/gsyerctx.html