Open In App

std::bit_xor in C++ with Examples

Improve
Improve
Like Article
Like
Save
Share
Report

The bit_xor is an inbuilt function in C++ which is used to perform bitwise_xor and return the result after applying the bitwise_xor operation on it’s arguments.

Header File:

#include <functional.h>

Template Class:

template <class T> struct bit_xor;

Parameters: It accepts a parameter T which is the type of the argument to be compared by the functional call.

Note:

  1. Objects of this class can be used on standard algorithms such as transform or accumulate.
  2. Member functions ( ‘operator()’ ) returns the bit_xor of its arguments.

We must include the library ‘functional’ and ‘algorithm’ to use bit_xor and transform() respectively.

Below is the illustration of bit_xor in C++:
Problem 1:




// C++ program to illustrate bit_xor in C++
  
#include <algorithm>
#include <functional> // to include bit_xor
#include <iostream>
#include <iterator>
using namespace std;
  
int main()
{
    // declaring the values
    int A[] = { 1, 2, 3, 4, 5, 6 };
    int B[] = { 6, 7, 8, 4, 5, 0 };
    int n = 6;
    // defining result
    int result[n];
  
    // transform is used to apply bitwise_xor
    // on the arguments A and B
    transform(A, end(A), B,
              result, bit_xor<int>());
  
    // printing the resulting array
    cout << "A xor B = ";
    for (const int& answer : result)
        cout << ' ' << answer;
  
    return 0;
}


Output:

A xor B =  7 5 11 0 0 6

Program 2:




// C++ program to illustrate bit_xor in C++
  
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
using namespace std;
  
int main()
{
    // declaring the values
    int A[] = { 0, 0xff, 15, 22 };
    int B[] = { 1, 255, 0xfa, 0x16 };
    int n = 4;
    // defining result
    int result[n];
  
    // transform is used to apply bitwise_xor
    // on the arguments A and B
    transform(A, end(A), B,
              result, bit_xor<int>());
  
    // printing the resulting array
    cout << "A xor B = ";
    for (const int& answer : result)
        cout << ' ' << answer;
  
    return 0;
}


Output:

A xor B =  1 0 245 0

Reference: https://en.cppreference.com/w/cpp/utility/functional/bit_xor



Last Updated : 01 May, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads