logo

swap() C++:ssa

Toiminto std::swap() on C++ Standard Template Libraryn (STL) sisäänrakennettu funktio, joka vaihtaa kahden muuttujan arvon.

Syntaksi:

swap(a, b)>

Parametrit:



java kartta esimerkki

Funktio hyväksyy kaksi pakollista parametria a ja b, jotka on vaihdettava. Parametrit voivat olla mitä tahansa tietotyyppiä.

Palautusarvo:

Funktio ei palauta mitään, se vaihtaa kahden muuttujan arvot. Alla olevat ohjelmat havainnollistavat swap()-funktiota:

Aika monimutkaisuus: O(1)

Tilan monimutkaisuus: O(1)

Ohjelma 1:

CPP




Yhdistä lajittelu

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

>

>

Lähtö

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

Ohjelma 2:

CPP


java merkkijonon liittäminen



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

>

binääripuutyypit

>

Lähtö

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