Difference between 2 swap options

Is there difference between swap (x, y) and temp = x; x = y; y = temp; ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void insertionSort (int array[], int size)
{
    int j;
    int temp;
    for( int i = 1; i < size; i++ )
    {
        j = i;
        while (j > 0 && array[j-1] > array[j] )
        {
            swap(array[j],array[j-1]);
            j--;
        }
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void insertionSort (int array[], int size)
{
    int j;
    int temp;
    for( int i = 1; i < size; i++ )
    {
        j = i;
        while (j > 0 && array[j-1] > array[j] )
        {
            temp = array[j];
            array[j] = array[j-1];
            array[j-1] = temp;
            j--;
        }
    }
}
not really... both ways are the same. std::swap just allows you to do a little bit of less typing.
The behavior of this function template is equivalent to:

1
2
3
4
template <class T> void swap ( T& a, T& b )
{
  T c(a); a=b; b=c;
} 


or

1
2
3
4
5
6
7
8
9
template <class T> void swap (T& a, T& b)
{
  T c(std::move(a)); a=std::move(b); b=std::move(c);
}

template <class T, size_t N> void swap (T &a[N], T &b[N])
{
  for (size_t i = 0; i<N; ++i) swap (a[i],b[i]);
}


in c++11.

http://www.cplusplus.com/reference/utility/swap/?kw=swap
Last edited on
thx, for telling me. Tho this forum is for "beginners" , I kinda dont understand template, class, ... :D

but thank you any way :D
Topic archived. No new replies allowed.