diff --git a/CPP17.md b/CPP17.md index 8d5b4b3..9e47a3b 100644 --- a/CPP17.md +++ b/CPP17.md @@ -33,6 +33,7 @@ C++17 includes the following new library features: - [parallel algorithms](#parallel-algorithms) - [std::sample](#stdsample) - [std::clamp](#stdclamp) +- [std::reduce](#stdreduce) ## C++17 Language Features @@ -548,6 +549,17 @@ std::clamp(0, -1, 1); // == 0 std::clamp(0, -1, 1, std::less<>{}); // == 0 ``` +### std::reduce +Fold over a given range of elements. Conceptually similar to `std::accumulate`, but `std::reduce` will perform the fold in parallel. Due to the fold being done in parallel, if you specify a binary operation, it is required to be associative and commutative. A given binary operation also should not change any element or invalidate any iterators within the given range. + +The default binary operation is std::plus with an initial value of 0. +```c++ +const std::array a{ 1, 2, 3 }; +std::reduce(std::cbegin(a), std::cend(a)); // == 6 +// Using a custom binary op: +std::reduce(std::cbegin(a), std::cend(a), 1, std::multiplies<>{}); // == 6 +``` + ## 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 3d59801..fae127b 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ C++17 includes the following new library features: - [parallel algorithms](#parallel-algorithms) - [std::sample](#stdsample) - [std::clamp](#stdclamp) +- [std::reduce](#stdreduce) C++14 includes the following new language features: - [binary literals](#binary-literals) @@ -1212,6 +1213,17 @@ std::clamp(0, -1, 1); // == 0 std::clamp(0, -1, 1, std::less<>{}); // == 0 ``` +### std::reduce +Fold over a given range of elements. Conceptually similar to `std::accumulate`, but `std::reduce` will perform the fold in parallel. Due to the fold being done in parallel, if you specify a binary operation, it is required to be associative and commutative. A given binary operation also should not change any element or invalidate any iterators within the given range. + +The default binary operation is std::plus with an initial value of 0. +```c++ +const std::array a{ 1, 2, 3 }; +std::reduce(std::cbegin(a), std::cend(a)); // == 6 +// Using a custom binary op: +std::reduce(std::cbegin(a), std::cend(a), 1, std::multiplies<>{}); // == 6 +``` + ## C++14 Language Features ### Binary literals