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 <algorithm>
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 <algorithm> 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.
1 2 3 4 5 |
template< class PopulationIterator, class SampleIterator, class Distance, class URBG > SampleIterator sample( PopulationIterator first_in, PopulationIterator last_in, SampleIterator output, Distance n, URBG&& function ); |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#include <iostream> #include <string> #include <vector> #include <iterator> #include <random> #include <algorithm> int main() { std::vector<std::string> vec_in {"This", "LearnCPlusPlus.org", "is", "really", "amazing","!"}; std::vector<std::string> vec_out; std::cout << "Input vector:"; for(auto v :vec_in) std::cout << v << " "; std::cout << std::endl; std::sample( vec_in.begin(), vec_in.end(), std::back_inserter(vec_out), 4, std::mt19937 {std::random_device{}()}); std::cout << "Output vector:"; for(auto v :vec_out) std::cout << v << ","; std::cout << std::endl; system("pause"); return 0; } |
Here is the output,
1 2 3 4 |
Input vector:This LearnCPlusPlus.org is really amazing ! Output vector:This,LearnCPlusPlus.org,really,amazing, |
For more details about this feature in C++17 standard, please see these papers; P0220R1 , N4562#alg.random.sample
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.