c语言中swap函数的参数,std :: swap()函数以及C ++ STL中的示例

std :: swap()

swap()是一个标准的库函数,它可以将任意两个对象交换b / w值。在C11中,它已移至标头下。以下是swap()的语法详细信息。

语法:void swap (T& a, T& b);

参数: T&a,T&b,它们是要交换的对象

返回类型: void-不返回任何内容。

用法:交换两个对象的黑白值

例子:

1)交换两种内置数据类型

在下面的示例中,我们看到如何使用std :: swap()函数交换两个整数。#include 

using namespace std;

int main(){

int a = 10, b = 20;

cout <

cout <

//立即交换

swap(a, b);

cout <

cout <

return 0;

}

输出:Before swapping:

//答: 10, b: 20

After swapping:

//答: 20, b: 10

2)交换两个用户定义的对象

在下面的示例中,我们看到如何使用std :: swap()函数交换两个用户定义的对象。在这里,我们定义了一个学生类,因为我们看到交换如何在他们之间交换内容。#include 

using namespace std;

class student {

public:

int roll;

string name;

int marks;    student()

{

roll = -1;

name = "";

marks = 0;

}

student(int r, string s, int m)

{

roll = r;

name = s;

marks = m;

}

};

void print(student t)

{

cout <

cout <

cout <

}

int main(){

student a(1, "Alice", 80);

student b(2, "Bob", 85);

cout <

cout <

print(a);

cout <

print(b);

//立即交换

swap(a, b);

cout <

cout <

print(a);

cout <

print(b);

return 0;

}

输出:Before swapping:

Student //答:

//滚动: 1

//名称: Alice

//标记: 80

Student b:

//滚动: 2

//名称: Bob

//标记: 85

After swapping:

Student //答:

//滚动: 2

//名称: Bob

//标记: 85

Student b:

//滚动: 1

//名称: Alice

//标记: 80

3)在两个向量(容器)之间交换

在下面的示例中,我们将看到如何交换两个向量的内容。同样,我们可以交换任何容器的be / w对象。#include 

using namespace std;

void print(vector a)

{

for (auto it : a) {

cout <

}

cout <

}

int main(){

vector a{ 10, 20, 30, 40 };

vector b{ 1, 2, 3, 4, 5, 6, 7 };

cout <

cout <

print(a);

cout <

print(b);

//立即交换

swap(a, b);

cout <

cout <

print(a);

cout <

print(b);

return 0;

}

输出:Before swapping:

Vector //答:

10 20 30 40

Vector b:

1 2 3 4 5 6 7

After swapping:

Vector //答:

1 2 3 4 5 6 7

Vector b:

10 20 30 40

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值