min_element.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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
  26. _Iter __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
  37. _Iter __min_element(_Iter __first, _Sent __last, _Comp __comp) {
  38. auto __proj = __identity();
  39. return std::__min_element<_Comp>(std::move(__first), std::move(__last), __comp, __proj);
  40. }
  41. template <class _ForwardIterator, class _Compare>
  42. _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _ForwardIterator
  43. min_element(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp)
  44. {
  45. static_assert(__has_forward_iterator_category<_ForwardIterator>::value,
  46. "std::min_element requires a ForwardIterator");
  47. static_assert(__is_callable<_Compare, decltype(*__first), decltype(*__first)>::value,
  48. "The comparator has to be callable");
  49. return std::__min_element<__comp_ref_type<_Compare> >(std::move(__first), std::move(__last), __comp);
  50. }
  51. template <class _ForwardIterator>
  52. _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _ForwardIterator
  53. min_element(_ForwardIterator __first, _ForwardIterator __last)
  54. {
  55. return _VSTD::min_element(__first, __last, __less<>());
  56. }
  57. _LIBCPP_END_NAMESPACE_STD
  58. _LIBCPP_POP_MACROS
  59. #endif // _LIBCPP___ALGORITHM_MIN_ELEMENT_H