// Swapping - interchange the values of two variables a and b. // illustration by bds 11/98 #include // no references or pointers, only swaps locally, fails the intention of swap. template void swap1( T x, T y ) { cout << " x = " << x << " and y = " << y << " entering swap1" << endl; T tmp = x; x = y; y = tmp; cout << " x = " << x << " and y = " << y << " exiting swap1" << endl; } // swapping using pointers template void swap2( T* x, T* y ) { cout << " x = " << *x << " and y = " << *y << " entering swap1" << endl; T tmp = *x; *x = *y; *y = tmp; cout << " x = " << *x << " and y = " << *y << " exiting swap1" << endl; } // swapping using references template void swap3( T& x, T& y ) { cout << " x = " << x << " and y = " << y << " entering swap1" << endl; T tmp = x; x = y; y = tmp; cout << " x = " << x << " and y = " << y << " exiting swap1" << endl; } int main() { int a = 1; int b = 2; cout << "a = " << a << " and b = " << b << " before swap1" << endl; swap1(a, b); cout << "a = " << a << " and b = " << b << " after swap1" << endl; swap2(&a, &b); cout << "a = " << a << " and b = " << b << " after swap2" << endl; swap3(a, b); cout << "a = " << a << " and b = " << b << " after swap3" << endl; }