minmax.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #ifndef _LIBCPP___ALGORITHM_MINMAX_H
  9. #define _LIBCPP___ALGORITHM_MINMAX_H
  10. #include <__algorithm/comp.h>
  11. #include <__algorithm/minmax_element.h>
  12. #include <__config>
  13. #include <__functional/identity.h>
  14. #include <__type_traits/is_callable.h>
  15. #include <__utility/pair.h>
  16. #include <initializer_list>
  17. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  18. # pragma GCC system_header
  19. #endif
  20. _LIBCPP_BEGIN_NAMESPACE_STD
  21. template<class _Tp, class _Compare>
  22. _LIBCPP_NODISCARD_EXT inline
  23. _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_SINCE_CXX14
  24. pair<const _Tp&, const _Tp&>
  25. minmax(_LIBCPP_LIFETIMEBOUND const _Tp& __a, _LIBCPP_LIFETIMEBOUND const _Tp& __b, _Compare __comp)
  26. {
  27. return __comp(__b, __a) ? pair<const _Tp&, const _Tp&>(__b, __a) :
  28. pair<const _Tp&, const _Tp&>(__a, __b);
  29. }
  30. template<class _Tp>
  31. _LIBCPP_NODISCARD_EXT inline
  32. _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_SINCE_CXX14
  33. pair<const _Tp&, const _Tp&>
  34. minmax(_LIBCPP_LIFETIMEBOUND const _Tp& __a, _LIBCPP_LIFETIMEBOUND const _Tp& __b)
  35. {
  36. return std::minmax(__a, __b, __less<>());
  37. }
  38. #ifndef _LIBCPP_CXX03_LANG
  39. template<class _Tp, class _Compare>
  40. _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14
  41. pair<_Tp, _Tp> minmax(initializer_list<_Tp> __t, _Compare __comp) {
  42. static_assert(__is_callable<_Compare, _Tp, _Tp>::value, "The comparator has to be callable");
  43. __identity __proj;
  44. auto __ret = std::__minmax_element_impl(__t.begin(), __t.end(), __comp, __proj);
  45. return pair<_Tp, _Tp>(*__ret.first, *__ret.second);
  46. }
  47. template<class _Tp>
  48. _LIBCPP_NODISCARD_EXT inline
  49. _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_SINCE_CXX14
  50. pair<_Tp, _Tp>
  51. minmax(initializer_list<_Tp> __t)
  52. {
  53. return std::minmax(__t, __less<>());
  54. }
  55. #endif // _LIBCPP_CXX03_LANG
  56. _LIBCPP_END_NAMESPACE_STD
  57. #endif // _LIBCPP___ALGORITHM_MINMAX_H