関数 std::swap() は、2 つの変数の値を交換する C++ 標準テンプレート ライブラリ (STL) の組み込み関数です。
構文:
swap(a, b)>
パラメーター:
ランダムc
この関数は、交換される 2 つの必須パラメータ a と b を受け入れます。パラメータは任意のデータ型にすることができます。
戻り値:
この関数は何も返しません。2 つの変数の値を交換します。以下のプログラムは 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;> }> |
>
np.どこ
>出力
Value of a before: Geeks Value of b before: function Value of a now: function Value of b now: Geeks>