I was wondering what the most efficient, in terms of operations, way of swapping integers is in c++, and why? Is something like:
int a =..., b = ...;
a = a + b;
b = a - b;
a = a - b;
more efficient than using a temporary? Are there any other more efficient ways? (not asking for just other ways to swap the ints) and why would they be more efficient?
Assigning values is always faster than doing arithmetic operations.
C++ implementation for std::swap is
template<typename T> void swap(T& t1, T& t2) {
T temp = std::move(t1); // or T temp(std::move(t1));
t1 = std::move(t2);
t2 = std::move(temp);
}
So to use a temporary variable is better than doing arithmetic trick.
And to use std::swap is even better because To reinvent the wheel in programming is never a good idea
The best way is to trust your compiler and use the C++ standard library functions. They are designed for each other.
std::swap
will win.
You could use an XOR swap for an int
(which doesn't require a temporary), but these days it would still perform less well than std::swap
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With