unique.hpp 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /// \file
  2. // Range v3 library
  3. //
  4. // Copyright Eric Niebler 2013-present
  5. // Copyright Gonzalo Brito Gadeschi 2014
  6. //
  7. // Use, modification and distribution is subject to the
  8. // Boost Software License, Version 1.0. (See accompanying
  9. // file LICENSE_1_0.txt or copy at
  10. // http://www.boost.org/LICENSE_1_0.txt)
  11. //
  12. // Project home: https://github.com/ericniebler/range-v3
  13. //
  14. // Implementation based on the code in libc++
  15. // http://http://libcxx.llvm.org/
  16. #ifndef RANGES_V3_ALGORITHM_UNIQUE_HPP
  17. #define RANGES_V3_ALGORITHM_UNIQUE_HPP
  18. #include <range/v3/range_fwd.hpp>
  19. #include <range/v3/algorithm/adjacent_find.hpp>
  20. #include <range/v3/functional/comparisons.hpp>
  21. #include <range/v3/functional/identity.hpp>
  22. #include <range/v3/functional/invoke.hpp>
  23. #include <range/v3/iterator/operations.hpp>
  24. #include <range/v3/range/access.hpp>
  25. #include <range/v3/range/concepts.hpp>
  26. #include <range/v3/range/dangling.hpp>
  27. #include <range/v3/range/traits.hpp>
  28. #include <range/v3/utility/static_const.hpp>
  29. #include <range/v3/detail/prologue.hpp>
  30. namespace ranges
  31. {
  32. /// \addtogroup group-algorithms
  33. /// @{
  34. RANGES_FUNC_BEGIN(unique)
  35. /// \brief template function \c unique
  36. ///
  37. /// range-based version of the \c unique std algorithm
  38. ///
  39. /// \pre `Rng` is a model of the `forward_range` concept
  40. /// \pre `I` is a model of the `forward_iterator` concept
  41. /// \pre `S` is a model of the `sentinel_for` concept
  42. /// \pre `C` is a model of the `relation` concept
  43. ///
  44. template(typename I, typename S, typename C = equal_to, typename P = identity)(
  45. requires sortable<I, C, P> AND sentinel_for<S, I>)
  46. constexpr I RANGES_FUNC(unique)(I first, S last, C pred = C{}, P proj = P{})
  47. {
  48. first = adjacent_find(std::move(first), last, ranges::ref(pred), ranges::ref(proj));
  49. if(first != last)
  50. {
  51. for(I i = next(first); ++i != last;)
  52. if(!invoke(pred, invoke(proj, *first), invoke(proj, *i)))
  53. *++first = iter_move(i);
  54. ++first;
  55. }
  56. return first;
  57. }
  58. /// \overload
  59. template(typename Rng, typename C = equal_to, typename P = identity)(
  60. requires sortable<iterator_t<Rng>, C, P> AND range<Rng>)
  61. constexpr borrowed_iterator_t<Rng> //
  62. RANGES_FUNC(unique)(Rng && rng, C pred = C{}, P proj = P{}) //
  63. {
  64. return (*this)(begin(rng), end(rng), std::move(pred), std::move(proj));
  65. }
  66. RANGES_FUNC_END(unique)
  67. namespace cpp20
  68. {
  69. using ranges::unique;
  70. }
  71. /// @}
  72. } // namespace ranges
  73. #include <range/v3/detail/epilogue.hpp>
  74. #endif