std::swap usage
📝 C++This snippet shows how to exchange the values of two variables using the efficient and standard std::swap function.
C++
#include <iostream>
#include <utility> int main() { int a = 5, b = 10; std::cout << "Before swap: a=" << a << " b=" << b << '\n'; std::swap(a, b); std::cout << "After swap: a=" << a << " b=" << b << '\n'; return 0;
}
Comments
I've seen people forget that std::swap calls the move constructor and assignment internally, so for some custom types with expensive moves, a hand-rolled swap using member swaps can actually be faster.