swap() programmā C++
Funkcija std::swap() ir C++ standarta veidņu bibliotēkā (STL) iebūvēta funkcija, kas apmaina divu mainīgo vērtību.
Sintakse:
swap(a, b)
Parametri:
Funkcija pieņem divus obligātos parametrus a un b, kas ir jāmaina. Parametri var būt jebkura veida dati.
Atgriešanas vērtība:
Funkcija neko neatgriež, tā apmaina abu mainīgo vērtības. Tālāk redzamās programmas ilustrē swap() funkciju:
Laika sarežģītība: O(1)
Kosmosa sarežģītība: O(1)
1. programma:
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;> }> |
Izvade
Value of a before: 10 Value of b before: 20 Value of a now: 20 Value of b now: 10
2. programma:
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;> }> |
Izvade
Value of a before: Geeks Value of b before: function Value of a now: function Value of b now: Geeks