swap function in cpp for array code example

Example 1: swap values in array c++

#include <algorithm>
#include <iostream>

using namespace std;

int main()
{
     int array[]={1, 2};
     cout<<array[0]<<" "<<array[1]<<endl;
     swap(array[0], array[1]);
     cout<<array[0]<<" "<<array[1];
     return 0;
}

Example 2: swap in cpp

int a{}, b{}, temp{};
cin >> a >> b;

  //===================== METHOD-1
   temp = a;
   a = b;
   b = temp;

  //===================== METHOD-2 ( XOR ^ )
  // example: a^b =  5^7
   a = a ^ b;   // 5^7
   b = a ^ b;   // 5 ^ 7 ^ 7  //5 ( 7 & 7 dismissed)
   a = a ^ b;   // 5 ^ 7 ^ 5  //7 ( 5 & 5 dismissed)

  //===================== METHOD-3  ( swap() )
  swap(a, b);

  cout << "a " << a << endl;
  cout << "b " << b << endl;

Tags:

Cpp Example