swap() in C++

Die Funktion std::swap() ist eine integrierte Funktion in der C++ Standard Template Library (STL), die den Wert zweier Variablen austauscht.

Syntax:

swap(a, b) 

Parameter:

Die Funktion akzeptiert zwei Pflichtparameter a und b, die ausgetauscht werden sollen. Die Parameter können einen beliebigen Datentyp haben.

Rückgabewert:

Die Funktion gibt nichts zurück, sie vertauscht die Werte der beiden Variablen. Die folgenden Programme veranschaulichen die swap()-Funktion:

Zeitkomplexität: O(1)

Raumkomplexität: O(1)

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

Ausgabe

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

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

Ausgabe

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