not1 and not2 function templates in C++
Hello, Learners here we will learn about two function templates std::not1
and std::not2
. These are used to create negator function objects.
std::not1
The std::not1
is a helper function available in C++ std
namespace. This function takes a unary function object as its arguments and returns a function object of unary_negate<Operator>
.
c++ code | not1 implementation
#include <iostream> // std::not1 #include <functional> // std::count_if #include <algorithm> using namespace std; struct IsOdd { bool operator() (const int &x) const { return x%2==1; } typedef int argument_type; }; //driver function int main () { int arr[] = {1,2,3,4,5}; int count = count_if (arr, arr+5, not1(IsOdd())); cout << "There are " << count << " even values available in the array.\n"; return 0; }
Output : There are 2 even values available in the array.
not1 function is true when the array element is even and false when the array element is odd. std::count_if
returns the number of occurrences in a range for which condition/pred is true. pred refers to Unary predicate which takes an argument and returns bool
std::not2
The std::not2
is a helper function available in C++ std
namespace. This function takes a binary function object as its arguments and returns a function object of binary_negate<Operator>
.
c++ code | not2 implementation
// std::cout #include <iostream> // std::not2, std::equal_to #include <functional> // std::mismatch #include <algorithm> // std::pair #include <utility> using namespace std; int main () { int arr1[] = {10,20,30,40,50}; int arr2[] = {0,15,30,45,60}; pair<int*,int*> first_match,first_mismatch; first_mismatch = mismatch (arr1, arr1+5, arr2, equal_to<int>()); first_match = mismatch (arr1, arr1+5, arr2, not2(equal_to<int>())); //second is public member to access //second element of paired values cout << "First mismatch in bar is " << *first_mismatch.second << '\n'; cout << "First match in bar is " << *first_match.second << '\n'; return 0; }
Output : First mismatch in bar is 0 First match in bar is 30
std::pair is a class, which couples together a pair of values. Here paired values may be of the same or different types. The mismatch function compares both the containers (here in this case arr1[] and arr2[]) to spot any mismatch of values. By default, the first elements of both containers those who do not match are returned by this function. To access returned paired first and second value we use public members first
and second
respectively.
Leave a Reply