vendredi 30 avril 2021

implementation of swap in c++ [duplicate]

Started to learn some C++ for competitive programming (already know some other languages) However got in a thinking for swap function of C++. Looked several resources including this one and this one also (Although the later one was a bit jargon for me(exhaling)). Most of them just tell what swap() do... ok, now I know what it do but I'm wondering How it's different form other common swap methods?

For example, If I have two numbers a and b than, a ^= b ^= a ^= b will also swap a and b

Infact, in general any object(same type as a and b) can be swapped with:

object temp = a;
a = b;
b = temp;

Obviously this will have overhead of creating extra object. But it's very simple to write... than why a specially dedicated inbuilt swap() is there? Does it have better performance and if so, how it's implemented without using third variable (thinking emoji) ? Or it's just for sake of completion?

Aucun commentaire:

Enregistrer un commentaire