std::bit_or in C++ with Examples
The bit_or is an inbuilt function in C++ which is used to perform bitwise_or and return the result after applying the bitwise_or operation on it’s arguments.
Header File:
#include <functional.h>
Template Class:
template <class T> struct bit_or;
Parameters: It accepts a parameter T which is the type of the argument to be compared by the functional call.
Note:
- Objects of this class can be used on standard algorithms such as transform or accumulate.
- Member functions ( ‘operator()’ ) returns the bitwise_or of its arguments.
We must include the library ‘functional’ and ‘algorithm’ to use bit_or and transform() respectively.
Below is the illustration of bit_or in C++:
Problem 1:
// C++ program to show the // functionality of bit_or #include <algorithm> // to include transform #include <functional> // to include bit_or #include <iostream> #include <iterator> using namespace std; int main() { // declaring the values int xyz[] = { -7, 2, 5, 100, 1029 }; int abc[] = { -4, 0, 5, 1, 1 }; int n = 5; // defining results int results[n]; // transform is used to apply // bitwise_or on the arguments transform(xyz, end(xyz), abc, results, bit_or< int >()); // printing the resulting array cout << "Results:" ; for ( const int & x : results) cout << ' ' << x; return 0; } |
Output:
Results: -3 2 5 101 1029
Some points to Remember
- Bitwise_or of a number with zero results into the number itself.
- Bitwise_or of two same numbers is also equal to that number itself
- If the number is odd it’s bit_or with 1 will result into same number
- If the number is even it’s bit_or with 1 will always results into “number+1”
Problem 2:
// C++ program to show the // functionality of bit_or #include <algorithm> #include <functional> #include <iostream> #include <iterator> using namespace std; int main() { // declaring the values // in form of hexadecimals int xyz[] = { 0, 1100 }; int abc[] = { 0xf, 0xf }; // defining results int results[2]; // transform is used to apply // bitwise_or on the arguments transform(xyz, end(xyz), abc, results, bit_or< int >()); // printing the resulting array cout << "Results:" ; for ( const int & x : results) cout << ' ' << x; return 0; } |
Output:
Results: 15 1103
Reference: https://en.cppreference.com/w/cpp/utility/functional/bit_or