
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 swapusing 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
以上是内存溢出为你收集整理的C++ swap函数模板及其用法全部内容,希望文章能够帮你解决C++ swap函数模板及其用法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)