swap


Motivation

When you want to swap the value of two variables, you must introduce a third because without it one of the original values would be lost:


int a = 5;
int b = 10;

// Manual swap using a temporary variable
int temp = a;
a = b;
b = temp;

std::swap is there to simplify this operation, making the code cleaner and less error-prone:


#include <utility>;

int a = 5;
int b = 10;

std::swap(a, b);