diff --git a/CPP17.md b/CPP17.md index 630325e..8d5b4b3 100644 --- a/CPP17.md +++ b/CPP17.md @@ -32,6 +32,7 @@ C++17 includes the following new library features: - [splicing for maps and sets](#splicing-for-maps-and-sets) - [parallel algorithms](#parallel-algorithms) - [std::sample](#stdsample) +- [std::clamp](#stdclamp) ## C++17 Language Features @@ -536,6 +537,17 @@ std::sample(ALLOWED_CHARS.begin(), ALLOWED_CHARS.end(), std::back_inserter(guid) std::cout << guid; // e.g. G1fW2 ``` +### std::clamp +Clamp given value between a lower and upper bound. +```c++ +std::clamp(42, -1, 1); // == 1 +std::clamp(-42, -1, 1); // == -1 +std::clamp(0, -1, 1); // == 0 + +// `std::clamp` also accepts a custom comparator: +std::clamp(0, -1, 1, std::less<>{}); // == 0 +``` + ## 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 8e92528..3d59801 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ C++17 includes the following new library features: - [splicing for maps and sets](#splicing-for-maps-and-sets) - [parallel algorithms](#parallel-algorithms) - [std::sample](#stdsample) +- [std::clamp](#stdclamp) C++14 includes the following new language features: - [binary literals](#binary-literals) @@ -1200,6 +1201,17 @@ std::sample(ALLOWED_CHARS.begin(), ALLOWED_CHARS.end(), std::back_inserter(guid) std::cout << guid; // e.g. G1fW2 ``` +### std::clamp +Clamp given value between a lower and upper bound. +```c++ +std::clamp(42, -1, 1); // == 1 +std::clamp(-42, -1, 1); // == -1 +std::clamp(0, -1, 1); // == 0 + +// `std::clamp` also accepts a custom comparator: +std::clamp(0, -1, 1, std::less<>{}); // == 0 +``` + ## C++14 Language Features ### Binary literals