How to implement the swap function when the type of an object is unknown

I am trying to implement all the functions STLmyself.

In the function, make_heapI need to swap two objects. Now, since I want it to be STL, how can I not change the list of arguments.

Therefore, I cannot declare the variable objectthat it points to first.

I also can not use swap without temporary variables

swap (RandomAccessIterator a,RandomAccessIterator b)
{
    *a = *a + *b;
    *b = *a - *b;
    *a = *a - *b;
}

because the operators +and -cannot be overloaded for this object, which are indicated by two pointers.

Here is my code:

template <class RandomAccessIterator>

void make_heap (RandomAccessIterator first,RandomAccessIterator last)
{

    int num_ele = (last - first) + 1;
    for (int i=num_ele-1;i>=1;i--)
    {
        if (first[i] < first[(i-1)/2])
        {
            swap (/* Here is where i am struck..! */);
        }
    }


}

PS: suppose that they objectsare comparable when <Operator.

+4
source share
4 answers

You can use something like (in C ++ 11):

void iter_swap(RandomAccessIterator a, RandomAccessIterator b)
{
    auto temp(std::move(*a));
    *a = std::move(*b);
    *b = std::move(temp);
}

or using std::iterator_traits

void iter_swap(RandomAccessIterator a, RandomAccessIterator b)
{
    std::iterator_traits<RandomAccessIterator>::value_type temp(std::move(*a));
    *a = std::move(*b);
    *b = std::move(temp);
}
+3

, , :

using std::swap;
swap(a,b);

using std::swap , swap, std::swap , , ADL. , .

: , , , , , , swap. ADL swap.

+1

You can implement swapas a template function

template<typename T>
void swap(T& a, T& b) {
    T c(a); a = b; b = c;
}

and call it from your code as:

swap(*a, *b);

Also in this way, the user can define a specialized specialization for replacement.

0
source

You can not use the XOR exchange algorithm here? http://en.wikipedia.org/wiki/XOR_swap_algorithm

-2
source

Source: https://habr.com/ru/post/1568905/


All Articles