The function returns random numbers in a specific range with the exception. Exceptions can be any number.

int randint (int min, int max, int exceptions{}) { ... } 

How do I write function parameters so that I can call a function like this:

 randint (0, 10, {4, 5, 6}); 

I need to transfer the array directly.

  • one
    Pointers are used to pass an array to a function. There are no other options - Andrej Levkovitch
  • Sorry, it would be convenient to pass exceptions in this way. And so it is necessary to create a temporary array with exceptions and transfer it already, it’s not very convenient :( - Mournehowl
  • Send initializer_list - Harry

1 answer 1

There are several options:

 int randint (int min, int max, ::std::initializer_list<int> values) int randint (int min, int max, ::std::array<int, 3> values) int randint (int min, int max, ::std::array_view<int> values) // аналог gsl::span 

You should not use pointers to pass an array to a function.

  • and why "Do not use pointers to pass an array to a function"? This is fundamental! In C, for example (direct C ++ ancestor), this is the only possible option. (Yes, and according to the question - for C ++ too) - Andrej Levkovitch
  • one
    @AndrejLevkovitch Well, that's right, this came from C, where this is the only option. However, in C ++ there are better alternatives. Actually raw pointers to data in C ++ are now needed except as raw iterators (and even better to make a wrapper) and to interact with the code in C. see CppCoreGuidelines - VTT
  • But according to the question: "Is it possible to pass an array directly to a function" is this not the best option? We have a sequence of bytes, the pointer to the beginning of which we pass to the function. - Andrej Levkovitch
  • @AndrejLevkovitch, the array cannot simply be passed as a pointer, you need to also transfer the size of the transferred array. Therefore, this makes no sense when there are normal C ++ solutions ( array and array_view ). VTT, in std there is no class array_view - ixSci
  • one
    @AndrejLevkovitch No, this is not the best option. Together with the pointer to the first element of the array, you must also transfer the size of the array, you may also annotate it for static verification, and of course you should not confuse it all in the function body. And so everything will be accurately transmitted in one parameter without unnecessary gestures. - VTT