matlab中swap函数代码,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

void swap(T &a, T &b)

{

T temp = a;

a = b;

b = temp;

}

这样的模板函数在标准 C++ 编译器附带的库中可用。该函数在 头文件中声明。

下面的程序演示了如何使用这个库模板函数来交换两个变量的内容:

// This program demonstrates the use of the swap function template.

#include

#include

#include // 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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值