How does std :: sort implement a swap operation using iterators only?

How can I implement, for example, the following

template <typename ITERATOR> void Swap (ITERATOR a, ITERATOR b) {
  ...
}

so Swap (a, b) changes the values ​​pointed to by a and b. In other words: How to create a third variable without knowing the data type?

+3
source share
5 answers

How to create a third variable without knowing the data type?

Use std::iterator_traits<ITERATOR>::value_type

+6
source

Exists iter_swaponly for this task:

std::iter_swap(a, b);

Also, if you can use C ++ 11, you can use decltype:

std::remove_reference<decltype(*a)>::type c = *a;
*a = *b;
*b = c;
+7
source

++ 11 std::remove_reference<decltype(*a)>::type, auto.

++ 03 :

// NOTE: This is for illustration only. If you are simply swapping
// values, use 'std::swap' instead of this, since that is specialised
// for many types to avoid unnecessary copy-assignment.
template <typename T> void value_swap(T & a, T & b) {
    T t = a;
    a = b;
    b = t;
}

template <typename I> void iterator_swap(I a, I b) {
    value_swap(*a, *b);
}

( ) std::iterator_traits<ITERATOR>::value_type. , - , iterator_traits iterator_traits .

, decltype; , GCC typeof. ​​, .

, std::iter_swap.

+4
template <typename ITERATOR> void Swap (ITERATOR a, ITERATOR b) {
  using std::swap;
  swap(*a,*b);
}
+3

, .

        iterator_traits<ITERATOR>::value_type temp = *a;
        *a = *b;
        *b = temp; 
+2

All Articles