Could I exchange two variables using tuple and tie?
int x, y;
....
std::tie(y, x) = std::make_tuple(x, y);
Could I exchange two variables using tuple and tie?
int x, y;
....
std::tie(y, x) = std::make_tuple(x, y);
std::make_tuple
creates a tuple instance, a copy of the arguments, so there's no problem using that to assign back to the original variables.
It is however non-idiomatic and more roundabout than simply using std::swap
, i.e. it's not code that one would expect, so I would not do it.
Regarding efficiency, just because that always comes up for such questions, that depends wholly on the compiler: all that can be said is that if it matters, measure.
The std::make_tuple
swapping uses a temporary, namely the tuple.
To exhcange the values of two variables of basic integral type, without using a temporary variable, you can just use the old XOR trick:
x ^= y;
y ^= x; // Sets y = original x value by cancelling the original y bits.
x ^= y; // Sets x = original y value by cancelling the original x bits.
This is well-defined for unsigned type. It's formally Undefined Behavior for signed type if any of the two values is negative any intermediate value is not representable in the type.