From 14e1e7e7c16f1c8b41baa8e883d2364dd29490d6 Mon Sep 17 00:00:00 2001 From: Danny Robson Date: Sun, 26 May 2019 10:11:01 +1000 Subject: [PATCH] random: choose should return iterators/pointers --- random.hpp | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/random.hpp b/random.hpp index 245df1ef..edcddda0 100644 --- a/random.hpp +++ b/random.hpp @@ -160,19 +160,30 @@ namespace cruft::random { /////////////////////////////////////////////////////////////////////////// - /// choose a value at random from an array + /// Choose a value at random from an array + /// + /// We return pointers (rather than values) so that we can return values + /// for empty containers without invalid dereferences. + /// + /// \return A pointer to the chosen value. template - T& + T* choose (T (&t)[N]) { std::uniform_int_distribution dist (0, N - 1); - return t[dist (generator ())]; + return &t[dist (generator ())]; } - //------------------------------------------------------------------------- + ///------------------------------------------------------------------------ + /// Choose a value at random from a container. + /// + /// We return iterators (rather than values) so that we can return values + /// for empty containers without invalid dereferences. + // + /// \return An iterator to the chosen value. template - auto + typename ContainerT::iterator choose (ContainerT &data, GeneratorT &&gen) { if (data.empty ()) @@ -188,9 +199,15 @@ namespace cruft::random { } - //------------------------------------------------------------------------- + ///------------------------------------------------------------------------ + /// Choose a value at random from a container. + /// + /// We return iterators (rather than values) so that we can return values + /// for empty containers without invalid dereferences. + /// + /// \return An iterator to the chosen value. template - auto + typename ContainerT::iterator choose (ContainerT &data) { return choose (data, generator ());