当前位置:   article > 正文

C++中的swap函数_c++中swap函数的结果小于0是什么意思

c++中swap函数的结果小于0是什么意思

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 );
  • 1
  • 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; 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

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; 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

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; 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/1016516
推荐阅读
  

闽ICP备14008679号