merge.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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_MERGE_H
  9. #define _LIBCPP___ALGORITHM_MERGE_H
  10. #include <__algorithm/comp.h>
  11. #include <__algorithm/comp_ref_type.h>
  12. #include <__algorithm/copy.h>
  13. #include <__config>
  14. #include <__iterator/iterator_traits.h>
  15. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  16. # pragma GCC system_header
  17. #endif
  18. _LIBCPP_BEGIN_NAMESPACE_STD
  19. template <class _Compare, class _InputIterator1, class _InputIterator2, class _OutputIterator>
  20. _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20
  21. _OutputIterator
  22. __merge(_InputIterator1 __first1, _InputIterator1 __last1,
  23. _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
  24. {
  25. for (; __first1 != __last1; ++__result)
  26. {
  27. if (__first2 == __last2)
  28. return _VSTD::copy(__first1, __last1, __result);
  29. if (__comp(*__first2, *__first1))
  30. {
  31. *__result = *__first2;
  32. ++__first2;
  33. }
  34. else
  35. {
  36. *__result = *__first1;
  37. ++__first1;
  38. }
  39. }
  40. return _VSTD::copy(__first2, __last2, __result);
  41. }
  42. template <class _InputIterator1, class _InputIterator2, class _OutputIterator, class _Compare>
  43. inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_SINCE_CXX20
  44. _OutputIterator
  45. merge(_InputIterator1 __first1, _InputIterator1 __last1,
  46. _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
  47. {
  48. return _VSTD::__merge<__comp_ref_type<_Compare> >(__first1, __last1, __first2, __last2, __result, __comp);
  49. }
  50. template <class _InputIterator1, class _InputIterator2, class _OutputIterator>
  51. inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_SINCE_CXX20
  52. _OutputIterator
  53. merge(_InputIterator1 __first1, _InputIterator1 __last1,
  54. _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result)
  55. {
  56. return _VSTD::merge(__first1, __last1, __first2, __last2, __result, __less<>());
  57. }
  58. _LIBCPP_END_NAMESPACE_STD
  59. #endif // _LIBCPP___ALGORITHM_MERGE_H