merge.h 2.3 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_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 _OutputIterator __merge(
  21. _InputIterator1 __first1,
  22. _InputIterator1 __last1,
  23. _InputIterator2 __first2,
  24. _InputIterator2 __last2,
  25. _OutputIterator __result,
  26. _Compare __comp) {
  27. for (; __first1 != __last1; ++__result) {
  28. if (__first2 == __last2)
  29. return std::copy(__first1, __last1, __result);
  30. if (__comp(*__first2, *__first1)) {
  31. *__result = *__first2;
  32. ++__first2;
  33. } else {
  34. *__result = *__first1;
  35. ++__first1;
  36. }
  37. }
  38. return std::copy(__first2, __last2, __result);
  39. }
  40. template <class _InputIterator1, class _InputIterator2, class _OutputIterator, class _Compare>
  41. inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _OutputIterator
  42. merge(_InputIterator1 __first1,
  43. _InputIterator1 __last1,
  44. _InputIterator2 __first2,
  45. _InputIterator2 __last2,
  46. _OutputIterator __result,
  47. _Compare __comp) {
  48. return std::__merge<__comp_ref_type<_Compare> >(__first1, __last1, __first2, __last2, __result, __comp);
  49. }
  50. template <class _InputIterator1, class _InputIterator2, class _OutputIterator>
  51. inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _OutputIterator
  52. merge(_InputIterator1 __first1,
  53. _InputIterator1 __last1,
  54. _InputIterator2 __first2,
  55. _InputIterator2 __last2,
  56. _OutputIterator __result) {
  57. return std::merge(__first1, __last1, __first2, __last2, __result, __less<>());
  58. }
  59. _LIBCPP_END_NAMESPACE_STD
  60. #endif // _LIBCPP___ALGORITHM_MERGE_H