minmax.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 pair<const _Tp&, const _Tp&>
  23. minmax(_LIBCPP_LIFETIMEBOUND const _Tp& __a, _LIBCPP_LIFETIMEBOUND const _Tp& __b, _Compare __comp) {
  24. return __comp(__b, __a) ? pair<const _Tp&, const _Tp&>(__b, __a) : pair<const _Tp&, const _Tp&>(__a, __b);
  25. }
  26. template <class _Tp>
  27. _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 pair<const _Tp&, const _Tp&>
  28. minmax(_LIBCPP_LIFETIMEBOUND const _Tp& __a, _LIBCPP_LIFETIMEBOUND const _Tp& __b) {
  29. return std::minmax(__a, __b, __less<>());
  30. }
  31. #ifndef _LIBCPP_CXX03_LANG
  32. template <class _Tp, class _Compare>
  33. _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 pair<_Tp, _Tp>
  34. minmax(initializer_list<_Tp> __t, _Compare __comp) {
  35. static_assert(__is_callable<_Compare, _Tp, _Tp>::value, "The comparator has to be callable");
  36. __identity __proj;
  37. auto __ret = std::__minmax_element_impl(__t.begin(), __t.end(), __comp, __proj);
  38. return pair<_Tp, _Tp>(*__ret.first, *__ret.second);
  39. }
  40. template <class _Tp>
  41. _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 pair<_Tp, _Tp>
  42. minmax(initializer_list<_Tp> __t) {
  43. return std::minmax(__t, __less<>());
  44. }
  45. #endif // _LIBCPP_CXX03_LANG
  46. _LIBCPP_END_NAMESPACE_STD
  47. #endif // _LIBCPP___ALGORITHM_MINMAX_H