intercambiar() en C++

La función std::intercambiar() es una función incorporada en la Biblioteca de plantillas estándar (STL) de C++ que intercambia el valor de dos variables.

Sintaxis:

swap(a, b) 

Parámetros:

La función acepta dos parámetros obligatorios a y b que deben intercambiarse. Los parámetros pueden ser de cualquier tipo de datos.

Valor de retorno:

La función no devuelve nada, intercambia los valores de las dos variables. Los programas siguientes ilustran la función swap():

Complejidad del tiempo: O(1)

Complejidad espacial: O(1)

Programa 1:

CPP




// C++ program for illustration of swap() function> #include> using> namespace> std;> int> main()> {> > int> a = 10;> > int> b = 20;> > cout < <> 'Value of a before: '> < < a < < endl;> > cout < <> 'Value of b before: '> < < b < < endl;> > // swap values of the variables> > swap(a, b);> > cout < <> 'Value of a now: '> < < a < < endl;> > cout < <> 'Value of b now: '> < < b < < endl;> > return> 0;> }>

Producción

Value of a before: 10 Value of b before: 20 Value of a now: 20 Value of b now: 10 

Programa 2:

CPP




#include> using> namespace> std;> int> main()> {> > string a => 'Geeks'> ;> > string b => 'function'> ;> > cout < <> 'Value of a before: '> < < a < < endl;> > cout < <> 'Value of b before: '> < < b < < endl;> > swap(a, b);> > cout < <> 'Value of a now: '> < < a < < endl;> > cout < <> 'Value of b now: '> < < b < < endl;> > return> 0;> }>

Producción

Value of a before: Geeks Value of b before: function Value of a now: function Value of b now: Geeks