void swap(int &a, int &b) { int temp = a; a = b; b = temp; }而在對一個陣列字串物件進行排序的時候,會需要以下函數:
void swap(string &a, string &b) { string temp = a; a = b; b = temp; }因為這兩個函數中程式碼的唯一區別就是被交換的變數的型別,所以這兩個函數的邏輯與所有其他類似函數的邏輯都可以使用同一個模板函數來表示:
template<class T> void swap(T &a, T &b) { T temp = a; a = b; b = temp; }這樣的模板函數在標準 C++ 編譯器附帶的庫中可用。該函數在
<algorithm>
標頭檔案中宣告。// This program demonstrates the use of the swap function template. #include <iostream> #include <string> #include <algorithm> // Needed for swap using namespace std; int main () { // Get and swap two chars char firstChar, secondChar; cout << "Enter two characters: "; cin >> firstChar >> secondChar; swap(firstChar, secondChar); cout << firstChar << " " << secondChar << endl; // Get and swap two ints int firstInt, secondInt; cout << "Enter two integers: "; cin >> firstInt >> secondInt; swap(firstInt, secondInt); cout << firstInt << " " << secondInt << endl; // Get and swap two strings cout << "Enter two strings: "; string firstString, secondString; cin >> firstString >> secondString; swap(firstString, secondString); cout << firstString << " " << secondString << endl; return 0; }程式輸出結果:
Enter two characters: a b
b a
Enter two integers: 12 45
45 12
Enter two strings: http://c.biancheng.net cyuyan
cyuyan http://c.biancheng.net