swap() în C++

Functia std::swap() este o funcție încorporată în biblioteca de șabloane standard (STL) C++ care schimbă valoarea a două variabile.

Sintaxă:

swap(a, b) 

Parametri:

Funcția acceptă doi parametri obligatorii a și b care urmează să fie schimbați. Parametrii pot fi de orice tip de date.

Valoare returnată:

Funcția nu returnează nimic, schimbă valorile celor două variabile. Programele de mai jos ilustrează funcția swap():

Complexitatea timpului: O(1)

Complexitatea spațiului: O(1)

Programul 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;> }>

Ieșire

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

Programul 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;> }>

Ieșire

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