What Is The New std::sample Algorithm In C++ 17?

The C++ 17 standard bring us a lot of useful methods, templates and algorithms. One of the great algorithms is std::sample defined in the header that samples at most n elements uniformly from a given range. In this post, we explain the std::sample algorithm and how we can use it with an mt19937 random generator.

What is the std::sample algorithm in C++ 17 and beyond?

The std::sample algorithm is defined in header that samples at most n elements uniformly from a given range into the output iterator and random numbers can be generated by using a random number generator function. Generally std::mt19937{} is used as random generator and std::random_device{}() is used random generator device.

The std::sample algorithm is defined as a template algorithm in C++17 as shown below.

Here, first_in and last_in are the iterators that defines range of input. n is number of elements to be sampled into output iterator, function is random number generator function.

Is there a full example about the std::sample algorithm in C++ 17 and beyond?

Here is a full example about std::sample in C++ 17.

Here is the output,

For more details about this feature in C++17 standard, please see these papers; P0220R1 , N4562#alg.random.sample

What Is The New stdsample Algorithm In C++ 17

C++ Builder is the easiest and fastest C and C++ compiler and IDE for building simple or professional applications on the Windows operating system. It is also easy for beginners to learn with its wide range of samples, tutorials, help files, and LSP support for code. RAD Studio’s C++ Builder version comes with the award-winning VCL framework for high-performance native Windows apps and the powerful FireMonkey (FMX) framework for UIs.

There is a free C++ Builder Community Edition for students, beginners, and startups; it can be downloaded from here. For professional developers, there are Professional, Architect, or Enterprise versions of C++ Builder and there is a trial version you can download from here.