C++中的swap函数

Introduction

Swapping is a simple operation in C++ which basically is the exchange of data or values among two variables of any data type. Considering both the variables are of the same data type.

The function and its working

The swap() function in C++, from the standard library, is a function that directly swaps values between two given variables of the same types.

swap( a , b );
  • a and b, both are variables of the same data type.
  • We pass both of them to the swap() function and the values at their respective addresses are exchanged among themselves.

The swap() function from the standard library in C++ can swap values
of any data type
including int, float, string, etc. and even data
structures like arrays, stacks, and queues, etc.

Now , let’s look at some examples !

Swapping two integer values

#include <iostream> 
using namespace std; 
int main() 
{ 
    int val1 = 2;
    int val2 = 5;
    
	swap(val1, val2);
	
	cout<<"New value of val1 = "<<val1<<endl;
	cout<<"New value of val2 = "<<val2<<endl;
    return 0; 
}

Swapping two string objects from the string header file

#include <iostream> 
#include <string>
using namespace std; 
int main() 
{ 
    string string1 = "String 1";
    string string2 = "String 2";
    
	swap(string1, string2);

	cout<<"New value of string1 = "<<string1<<endl;
	cout<<"New value of string2 = "<<string2<<endl;
	
    return 0; 
}

Swapping arrays using the swap() function

#include <iostream> 
using namespace std; 
int main() 
{ 
    int array1[3] = {1,2,3};
    int array2[3] = {2,4,6};
    int i;

	swap(array1, array2);
	
	cout<<"New value of array1 = "<<endl;
	for(i=0;i<3;i++)
		cout<<" "<<array1[i];
		
	cout<<"\nNew value of array2 = "<<endl;
	for(i=0;i<3;i++)
		cout<<" "<<array2[i];
	 
    return 0; 
}

References:https://www.journaldev.com/37269/swap-function-in-c-plus-plus

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值