how can i make swapping for 2 variables in more than 2 ways ??

Question is confusing.. What do you mean "make swapping"?

There are many ways to swap two variables..

``````std::swap(variable_a, variable_b);

//OR

template<class T>
void do_swap(T& a, T& b)
{
T temp = std::move(a);
a = std::move(b);
b = std::move(temp);
}

//OR

template<typename T>
void do_swap(T& a, T& b) …``````

## All 3 Replies

Question is confusing.. What do you mean "make swapping"?

There are many ways to swap two variables..

``````std::swap(variable_a, variable_b);

//OR

template<class T>
void do_swap(T& a, T& b)
{
T temp = std::move(a);
a = std::move(b);
b = std::move(temp);
}

//OR

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

//OR

template<typename T>
void do_swap(T* a, T* b)
{
T temp = *b;
*b = *a;
*a = temp;
}

//OR

template<typename T>
void do_swap(T* a, T* b)
{
*a ^= *b;
*b ^= *a;
*a ^= *b;
}

//OR

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

//OR

void do_swap(void* a, void* b, size_t size) //Usage: do_swap(&va, &vb, sizeof(va));
{
uint8_t* c = static_cast<uint8_t*>(a);
uint8_t* d = static_cast<uint8_t*>(b);

int i;
uint8_t t = 0;
for (i = 0; i < size; ++i)
{
t = c[i];
c[i] = d[i];
d[i] = t;
}
}
``````

Thanks triumphost. i found that helpful to me as well.

oh! thanks so much :) ..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.