C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了C++ swap函数模板及其用法大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
在许多应用程序中,都有交换相同类型的两个变量内容的需要。例如,在对整数数组进行排序时,将需要一个函数来交换两个变量的值,如下所示:
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

大佬总结

以上是大佬教程为你收集整理的C++ swap函数模板及其用法全部内容,希望文章能够帮你解决C++ swap函数模板及其用法所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: