min_element.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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_MIN_ELEMENT_H
  9. #define _LIBCPP___ALGORITHM_MIN_ELEMENT_H
  10. #include <__algorithm/comp.h>
  11. #include <__algorithm/comp_ref_type.h>
  12. #include <__config>
  13. #include <__functional/identity.h>
  14. #include <__functional/invoke.h>
  15. #include <__iterator/iterator_traits.h>
  16. #include <__type_traits/is_callable.h>
  17. #include <__utility/move.h>
  18. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  19. # pragma GCC system_header
  20. #endif
  21. _LIBCPP_PUSH_MACROS
  22. #include <__undef_macros>
  23. _LIBCPP_BEGIN_NAMESPACE_STD
  24. template <class _Comp, class _Iter, class _Sent, class _Proj>
  25. inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _Iter
  26. __min_element(_Iter __first, _Sent __last, _Comp __comp, _Proj& __proj) {
  27. if (__first == __last)
  28. return __first;
  29. _Iter __i = __first;
  30. while (++__i != __last)
  31. if (std::__invoke(__comp, std::__invoke(__proj, *__i), std::__invoke(__proj, *__first)))
  32. __first = __i;
  33. return __first;
  34. }
  35. template <class _Comp, class _Iter, class _Sent>
  36. _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _Iter __min_element(_Iter __first, _Sent __last, _Comp __comp) {
  37. auto __proj = __identity();
  38. return std::__min_element<_Comp>(std::move(__first), std::move(__last), __comp, __proj);
  39. }
  40. template <class _ForwardIterator, class _Compare>
  41. _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _ForwardIterator
  42. min_element(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp) {
  43. static_assert(
  44. __has_forward_iterator_category<_ForwardIterator>::value, "std::min_element requires a ForwardIterator");
  45. static_assert(
  46. __is_callable<_Compare, decltype(*__first), decltype(*__first)>::value, "The comparator has to be callable");
  47. return std::__min_element<__comp_ref_type<_Compare> >(std::move(__first), std::move(__last), __comp);
  48. }
  49. template <class _ForwardIterator>
  50. _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _ForwardIterator
  51. min_element(_ForwardIterator __first, _ForwardIterator __last) {
  52. return std::min_element(__first, __last, __less<>());
  53. }
  54. _LIBCPP_END_NAMESPACE_STD
  55. _LIBCPP_POP_MACROS
  56. #endif // _LIBCPP___ALGORITHM_MIN_ELEMENT_H