Junior — Middle
Could you explain the concept of swap idiom and how it is used in programming?
sobes.tech AI
Answer from AI
Swap idiom is a method of exchanging the values of two variables without using a temporary variable. In C++, it is often implemented using the standard function std::swap, which efficiently swaps the contents.
Example of manual swap implementation in C++:
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
Or using XOR operation (although less readable and potentially problematic with the same addresses):
a ^= b;
b ^= a;
a ^= b;
The swap idiom is useful for optimization, for example, when implementing assignment operators to ensure safe and efficient copying of objects.