swap() in C++
De functie std::wissel() is een ingebouwde functie in de C++ Standard Template Library (STL) die de waarde van twee variabelen verwisselt.
Syntaxis:
swap(a, b)
Parameters:
De functie accepteert twee verplichte parameters a en b die moeten worden verwisseld. De parameters kunnen van elk gegevenstype zijn.
Winstwaarde:
De functie retourneert niets, maar verwisselt de waarden van de twee variabelen. Onderstaande programma's illustreren de functie swap():
Tijdcomplexiteit: O(1)
Ruimtecomplexiteit: O(1)
Programma 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;> }> |
Uitvoer
Value of a before: 10 Value of b before: 20 Value of a now: 20 Value of b now: 10
Programma 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;> }> |
Uitvoer
Value of a before: Geeks Value of b before: function Value of a now: function Value of b now: Geeks