From c0e0f37bd00efdf208837e943f218815805a7243 Mon Sep 17 00:00:00 2001 From: Anthony Calandra Date: Mon, 20 Feb 2023 21:12:27 -0500 Subject: [PATCH] Add std::not_fn. --- CPP17.md | 14 ++++++++++++++ README.md | 14 ++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/CPP17.md b/CPP17.md index 3294986..f0b285a 100644 --- a/CPP17.md +++ b/CPP17.md @@ -36,6 +36,7 @@ C++17 includes the following new library features: - [std::reduce](#stdreduce) - [prefix sum algorithms](#prefix-sum-algorithms) - [gcd and lcm](#gcd-and-lcm) +- [std::not_fn](#stdnot_fn) ## C++17 Language Features @@ -600,6 +601,19 @@ std::gcd(p, q); // == 3 std::lcm(p, q); // == 9 ``` +### std::not_fn +Utility function that returns the negation of the result of the given function. +```c++ +const std::ostream_iterator ostream_it{ std::cout, " " }; +const auto is_even = [](const auto n) { return n % 2 == 0; }; +std::vector v{ 0, 1, 2, 3, 4 }; + +// Print all even numbers. +std::copy_if(std::cbegin(v), std::cend(v), ostream_it, is_even); // 0 2 4 +// Print all odd (not even) numbers. +std::copy_if(std::cbegin(v), std::cend(v), ostream_it, std::not_fn(is_even)); // 1 3 +``` + ## 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 ead9967..7da806c 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,7 @@ C++17 includes the following new library features: - [std::reduce](#stdreduce) - [prefix sum algorithms](#prefix-sum-algorithms) - [gcd and lcm](#gcd-and-lcm) +- [std::not_fn](#stdnot_fn) C++14 includes the following new language features: - [binary literals](#binary-literals) @@ -1264,6 +1265,19 @@ std::gcd(p, q); // == 3 std::lcm(p, q); // == 9 ``` +### std::not_fn +Utility function that returns the negation of the result of the given function. +```c++ +const std::ostream_iterator ostream_it{ std::cout, " " }; +const auto is_even = [](const auto n) { return n % 2 == 0; }; +std::vector v{ 0, 1, 2, 3, 4 }; + +// Print all even numbers. +std::copy_if(std::cbegin(v), std::cend(v), ostream_it, is_even); // 0 2 4 +// Print all odd (not even) numbers. +std::copy_if(std::cbegin(v), std::cend(v), ostream_it, std::not_fn(is_even)); // 1 3 +``` + ## C++14 Language Features ### Binary literals