Program to swap two variables of any type

INDEX OF ALL C++ PROGRAMS

Generic approach can be used to swap two numbers of any data type. In this approach generic types are used as parameter in program, so they work for different data structures and data types. Template function swap(a,b) was used in this program, which creates different versions of swap() for interchanging  different data types like int, float and char.

Templates used are defined with a parameter which replaces the specified data type at the time of actual use of class or function. Below is the c++ program to swap two variables of any data type

 

#include<iostream>

using namespace std;

template <class T>
void swap(T &x, T &y)

{

T temp =x;
x=y;
y=temp;

}

void interchange(int m,int n, float a, float b, char p, char q)
{
cout<<"m and n before swap :"<<m<<" "<<n<<endl;
std::swap(m,n);
cout<<"m and n after swap :"<<m<<" "<<n<<endl;

cout<<"a and b before swap :"<<a<<" "<<b<<endl;
std::swap(a,b);
cout<<"a and b after swap :"<<a<<" "<<b<<endl;

cout<<"p and q before swap :"<<p<<" "<<q<<endl;
std::swap(p,q);
cout<<"p and q after swap :"<<p<<" "<<q<<endl;
}

int main()
{

interchange (10,20,11.22,12.32,'a','b');
//return 0;	

}

Output :

m and n before swap :10 20
m and n after swap :20 10
a and b before swap :11.22 12.32
a and b after swap :12.32 11.22
p and q before swap :a b
p and q after swap :b a

In this program, functions were overloaded that can be used with different types of the data.

For example :

void interchange(int m,int n, float a, float b, char p, char q)

{

swap(m,n);// swap integers

swap(a,b); // swap float values

swap(p,q); // swap characters

To know the meaning of various keywords visit : c++ keywords-meanings

One Response

  1. kretikus

    Your source code does not test your swap function. Here a corrected version:

    #include

    template
    void swap(T &x, T &y)
    {
    T temp =x;
    x=y;
    y=temp;
    }

    void interchange(int m,int n, float a, float b, char p, char q)
    {
    std::cout<<"m and n before swap :"<<m<<" "<<n<<std::endl;
    swap(m,n);
    std::cout<<"m and n after swap :"<<m<<" "<<n<<std::endl;

    std::cout<<"a and b before swap :"<<a<<" "<<b<<std::endl;
    swap(a,b);
    std::cout<<"a and b after swap :"<<a<<" "<<b<<std::endl;

    std::cout<<"p and q before swap :"<<p<<" "<<q<<std::endl;
    swap(p,q);
    std::cout<<"p and q after swap :"<<p<<" "<<q<<std::endl;
    }

    int main(int argc, char* argv[])
    {
    interchange (10,20,11.22,12.32,'a','b');

    return 0;
    }

    Reply

What you Think? Share your Views