logo

swap() i C++

Funktionen std::swap() är en inbyggd funktion i C++ Standard Template Library (STL) som byter ut värdet på två variabler.

Syntax:

swap(a, b)>

Parametrar:



sträng i array i c

Funktionen accepterar två obligatoriska parametrar a och b som ska bytas. Parametrarna kan vara av vilken datatyp som helst.

Returvärde:

Funktionen returnerar ingenting, den byter ut värdena på de två variablerna. Program nedan illustrerar swap()-funktionen:

Tidskomplexitet: O(1)

Utrymmes komplexitet: O(1)

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

binär till bcd

>

>

Produktion

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

Program 2:

CPP

sträng till jsonobject




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

mysql skapa användare

>

>

Produktion

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