Jump to content

[C++] Interschimbarea a doua variabile


Recommended Posts

Am vazut de multe ori ca inca folositi o variabila auxiliara pentru a interschimba doua variabile intre ele.

Exista insa un mod mult mai usor de a face asta, utilizand functia std::swap din biblioteca algorithm sau utility incepand cu C++11.

Va voi prezenta diferite moduri de a interschimba doua variabile:

int a = 7, b = 5;

Folosind functia std::swap:

std::swap(a, b);

Folosind o variabila auxiliara:

int temp = a;
a = b;
b = a;

Folosind scaderi si adunari:

a += b; // a devine 7 + 5 = 12
b = a - b; // b devine 12 - 5 = 7
a -= b; // a devine 12 - 7 = 5

Folosind operatii pe biti, anume XOR (aici ai un articol):

a ^= b;
b ^= a;
a ^= b;

Ca performanta, am rulat fiecare varianta de 1.000 de ori:

swap_using_std_func: 9363 microseconds
swap_using_third_var: 2105 microseconds
swap_using_adds_and_substractions: 1702 microseconds
swap_using_xor: 1650 microseconds


Edited by Vesca
Link to comment
Share on other sites

This topic is now closed to further replies.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.