Horizon
Loading...
Searching...
No Matches
shuffle.hpp
Go to the documentation of this file.
1
2// Range v3 library
3//
4// Copyright Eric Niebler 2014-present
5//
6// Use, modification and distribution is subject to the
7// Boost Software License, Version 1.0. (See accompanying
8// file LICENSE_1_0.txt or copy at
9// http://www.boost.org/LICENSE_1_0.txt)
10//
11// Project home: https://github.com/ericniebler/range-v3
12//
13#ifndef RANGES_V3_ALGORITHM_SHUFFLE_HPP
14#define RANGES_V3_ALGORITHM_SHUFFLE_HPP
15
16#include <cstdint>
17#include <utility>
18
20
29#include <range/v3/utility/static_const.hpp>
31
32#include <range/v3/detail/prologue.hpp>
33
34namespace ranges
35{
38 RANGES_FUNC_BEGIN(shuffle)
39
40
41 template(typename I, typename S, typename Gen = detail::default_random_engine &)(
42 requires random_access_iterator<I> AND sentinel_for<S, I> AND
43 permutable<I> AND
44 uniform_random_bit_generator<std::remove_reference_t<Gen>> AND
45 convertible_to<invoke_result_t<Gen &>, iter_difference_t<I>>)
46 I RANGES_FUNC(shuffle)(I const first,
47 S const last,
48 Gen && gen = detail::get_random_engine()) //
49 {
50 auto mid = first;
51 if(mid == last)
52 return mid;
53 using D1 = iter_difference_t<I>;
54 using D2 =
56 std::uniform_int_distribution<D2> uid{};
57 using param_t = typename decltype(uid)::param_type;
58 while(++mid != last)
59 {
60 RANGES_ENSURE(mid - first <= PTRDIFF_MAX);
61 if(auto const i = uid(gen, param_t{0, D2(mid - first)}))
62 ranges::iter_swap(mid - i, mid);
63 }
64 return mid;
65 }
66
68 template(typename Rng, typename Gen = detail::default_random_engine &)(
70 uniform_random_bit_generator<std::remove_reference_t<Gen>> AND
71 convertible_to<invoke_result_t<Gen &>,
72 iter_difference_t<iterator_t<Rng>>>)
73 borrowed_iterator_t<Rng> //
74 RANGES_FUNC(shuffle)(Rng && rng, Gen && rand = detail::get_random_engine()) //
75 {
76 return (*this)(begin(rng), end(rng), static_cast<Gen &&>(rand));
77 }
78
79 RANGES_FUNC_END(shuffle)
80
81 namespace cpp20
82 {
83 using ranges::shuffle;
84 }
86} // namespace ranges
87
88#include <range/v3/detail/epilogue.hpp>
89
90#endif
The permutable concept.
The random_access_iterator concept.
The random_access_range concept.
The sentinel_for concept.
The uniform_random_bit_generator concept.
decltype(begin(declval(Rng &))) iterator_t
Definition access.hpp:698
typename detail::_cond< If >::template invoke< Then, Else > conditional_t
Select one type or another depending on a compile-time Boolean.
Definition meta.hpp:1148