La funció std::swap() és una funció integrada a la biblioteca de plantilles estàndard (STL) de C++ que intercanvia el valor de dues variables.
Sintaxi:
swap(a, b)>
Paràmetres:
vaja conceptes en java
La funció accepta dos paràmetres obligatoris a i b que s'han d'intercanviar. Els paràmetres poden ser de qualsevol tipus de dades.
Valor de retorn:
La funció no retorna res, intercanvia els valors de les dues variables. Els programes següents il·lustren la funció swap():
Complexitat temporal: O(1)
Complexitat espacial: O(1)
Programa 1:
CPP
generador de cadenes java
// 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;> }> |
>
>Sortida
Value of a before: 10 Value of b before: 20 Value of a now: 20 Value of b now: 10>
Programa 2:
CPP
format de data a cadena
#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;> }> |
>
la sessió ha caducat
>Sortida
Value of a before: Geeks Value of b before: function Value of a now: function Value of b now: Geeks>