+ 2

What is the fastest way to swap two numbers?

I know that it doesn't matter much at college level but in industry and the STL implementations, which algorithm of swapping is used?

10th Mar 2019, 10:28 AM
Sudesh Pawar
Sudesh Pawar - avatar
5 odpowiedzi
+ 3
C++ uses this. template <typename T> void swap(T& t1, T& t2) { T temp = std::move(t1); t1 = std::move(t2); t2 = std::move(temp); }
10th Mar 2019, 12:01 PM
Schindlabua
Schindlabua - avatar
+ 3
▪Swap integers without a temporary variable: a ^= b; // int temp = b b ^= a; // b = a a ^= b; // a = temp
11th Mar 2019, 5:29 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 2
https://code.sololearn.com/cBe8l52trUQU/?ref=app The fastest way is to use xor bitwise operator. -> you don't need a third variable
10th Mar 2019, 11:01 AM
Théophile
Théophile - avatar
+ 2
#include <algorithm> swap (a, b);
12th Mar 2019, 9:49 AM
BlackFAN
BlackFAN - avatar