swap() у C++

Функція std::swap() є вбудованою функцією стандартної бібліотеки шаблонів C++ (STL), яка міняє значення двох змінних.

Синтаксис:

swap(a, b) 

Параметри:

Функція приймає два обов’язкові параметри a і b, які потрібно поміняти місцями. Параметри можуть мати будь-який тип даних.

Повернене значення:

Функція нічого не повертає, вона міняє значення двох змінних. Програми нижче ілюструють функцію swap():

Часова складність: О(1)

Космічна складність: О(1)

Програма 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;> }>

Вихід

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

Програма 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;> }>

Вихід

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