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

  • 头文件<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的引用
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容