# C++ Notes: swap - references, pointers, STL, templates

Here is the classic `swap` function implemented in four different styles: using references, using pointers, using templates with references, and using the Standard Template Library `swap` from `<algorithm>`.

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
    // arrayptr/swap-ref-ptr-stl.cpp - Versions of swap
    // 2004-01-26 Rodenbach - Fred Swartz

    #include <iostream>
    #include <algorithm>
    using namespace std;

    //====================================== prototypes
    void swap_ref(int& a, int& b);
    void swap_ptr(int* a, int* b);

    //=========================================== swap_tpl
    template <class T>void swap_tpl(T& a, T& b) {
        T temp = a;
        a = b;
        b = temp;
    }

    //=========================================== main
    int main() {
        int x = 1;
        int y = 2;

        //std::cout << "start   : x = " << x << ", y = " << y << std::endl;

        std::swap(x, y);
        cout << "swap    : x = " << x << ", y = " << y << std::endl;

        swap_ref(x, y);
        cout << "swap_ref: x = " << x << ", y = " << y << std::endl;

        swap_ptr(&x, &y);
        cout << "swap_ptr: x = " << x << ", y = " << y << std::endl;

        swap_tpl(x, y);
        cout << "swap_tpl: x = " << x << ", y = " << y << std::endl;

        system("PAUSE");
    }

    //=========================================== swap_ref
    void swap_ref(int& a, int& b) {
        int temp = a;
        a = b;
        b = temp;
    }

    //=========================================== swap_ptr
    void swap_ptr(int* a, int* b) {
        int temp = *a;
        *a = *b;
        *b = temp;
    }