函數std :: swap()是C ++标準模闆庫(STL)中的内置函數,該函數交換兩個變量的值。
句法:
swap(a,b)
參數:該函數接受兩個必須交換的必需參數a和b。參數可以是任何資料類型。
傳回值:該函數不傳回任何内容,它交換兩個變量的值。
下面的程式說明了swap()函數:
示例一:
#include <bits/stdc++.h>
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
示例二:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string a = "ABCD";
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: ABCD
Value of b before: function
Value of a now: function
Value of b now: ABCD
每天學點小知識,希望對你有幫助~
另外如果你想更好的提升你的程式設計能力,學好C語言C++程式設計!彎道超車,快人一步!筆者這裡或許可以幫到你~
C語言C++程式設計學習交流圈子【點選進入】微信公衆号:C語言程式設計學習基地
分享(源碼、項目實戰視訊、項目筆記,基礎入門教程)
歡迎轉行和學習程式設計的夥伴,利用更多的資料學習成長比自己琢磨更快哦!