Swap is an inline function used to exchanging the values of the variables.
For example:
data_item x := 1
data_item y := 0
swap (x, y);
After swap() is performed, x will contain the value 0 and y will contain 1.
There are different methods used for swapping, they are as follows:
Temporary Variable:
Syntax:
define swap (x, y)
temp := x
x := y
y := temp
This is the simplest way to swap two variables but it uses extra memory.
Swap through Addition and Subtraction:
Syntax:
a = a + b;
b = a %u2013 b;
a = a %u2013 b;
It swaps two variables by adding and subtracting their values. But it can only swap numeric variables; it may not be possible or logical to add or subtract complex data types, like containers and it does not work generally for floating-point values, because floating-point arithmetic is non-associative.
XOR Swap:
Syntax:
X := X XOR Y
Y := Y XOR X
X := X XOR Y
It is a commutative operation which does not require temporary storage.
Swapping Containers:
Syntax:
template <class T>
void swap(T& a, T& b);
Containers which allocate memory from the heap using pointers may be swapped in a single operation, by swapping the pointers alone. The Standard Template Library overloads its built-in swap function to exchange the contents of containers
Parallel Assignment:
Syntax:
a, b := b, a
Multi-core processors facilitating parallel computing, two or more operations can be performed at once.
boost::swap() is same as std::swap(). Boost libraries offer specializations for swapping data that are defined in the namespace boost, boost::swap() can take advantage of them.
Program:
#include <boost/swap.hpp>#include <boost/array.hpp>#include <iostream>int main()
{
int A = 1;
int B = 2;
char C = 'p';
char D = 'q';
boost::swap(A, B);
boost::swap(C, D);
std::cout << A << B << '\n';
std::cout << C << D << '\n';
boost::array<int, 1> a1{};
boost::array<int, 1> a2{};
boost::array<int, 1> a3{};
boost::array<int, 1> a4{};
boost::swap(a1, a2);
boost::swap(a3, a4);
std::cout << a1[0] << a2[0] << a3[0] << a4[0] << '\n';
}
Output:
21
qp
0000
Comments