swap() w C++

Funkcja std::zamień() to wbudowana funkcja w standardowej bibliotece szablonów C++ (STL), która zamienia wartości dwóch zmiennych.

Składnia:

swap(a, b) 

Parametry:

Funkcja przyjmuje dwa obowiązkowe parametry a i b, które należy zamienić. Parametry mogą być dowolnego typu danych.

Wartość zwracana:

Funkcja nic nie zwraca, zamienia wartości obu zmiennych. Poniższe programy ilustrują funkcję swap():

Złożoność czasowa: O(1)

Złożoność przestrzeni: 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;> }>

Wyjście

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

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

Wyjście

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