diff --git a/CPP17.md b/CPP17.md index 51e4683..bb41ca8 100644 --- a/CPP17.md +++ b/CPP17.md @@ -31,6 +31,7 @@ C++17 includes the following new library features: - [std::byte](#stdbyte) - [splicing for maps and sets](#splicing-for-maps-and-sets) - [parallel algorithms](#parallel-algorithms) +- [std::sample](#stdsample) ## C++17 Language Features @@ -522,6 +523,18 @@ auto result1 = std::find(std::execution::par, std::begin(longVector), std::end(l auto result2 = std::sort(std::execution::seq, std::begin(longVector), std::end(longVector)); ``` +### std::sample +Samples n elements in the given sequence (without replacement) where every element has an equal chance of being selected. +```c++ +const std::string ALLOWED_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; +std::string guid; +// Sample 5 characters from ALLOWED_CHARS. +std::sample(ALLOWED_CHARS.begin(), ALLOWED_CHARS.end(), std::back_inserter(guid), + 5, std::mt19937{ std::random_device{}() }); + +std::cout << guid; // e.g. G1fW2 +``` + ## Acknowledgements * [cppreference](http://en.cppreference.com/w/cpp) - especially useful for finding examples and documentation of new library features. * [C++ Rvalue References Explained](http://thbecker.net/articles/rvalue_references/section_01.html) - a great introduction I used to understand rvalue references, perfect forwarding, and move semantics. diff --git a/README.md b/README.md index 82132c6..21b2c13 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ C++17 includes the following new library features: - [std::byte](#stdbyte) - [splicing for maps and sets](#splicing-for-maps-and-sets) - [parallel algorithms](#parallel-algorithms) - +- [std::sample](#stdsample) C++14 includes the following new language features: - [binary literals](#binary-literals) @@ -1184,6 +1184,18 @@ auto result1 = std::find(std::execution::par, std::begin(longVector), std::end(l auto result2 = std::sort(std::execution::seq, std::begin(longVector), std::end(longVector)); ``` +### std::sample +Samples n elements in the given sequence (without replacement) where every element has an equal chance of being selected. +```c++ +const std::string ALLOWED_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; +std::string guid; +// Sample 5 characters from ALLOWED_CHARS. +std::sample(ALLOWED_CHARS.begin(), ALLOWED_CHARS.end(), std::back_inserter(guid), + 5, std::mt19937{ std::random_device{}() }); + +std::cout << guid; // e.g. G1fW2 +``` + ## C++14 Language Features ### Binary literals