exchange() Function in C++ 14
Last Updated :
28 Jun, 2022
The exchange() function is a built-in function in C++ 14 defined in the <utility> header. The exchange() function copies new value to old value and it will return the old value.
Syntax:
exchange(old, new)
Parameters: The function needs two parameters.
- The parameter needs to be set.
- The parameter with which we wanted to set our parameter 1
Return Value: It returns the old value which means the parameter that needs to be set
Example 1:
C++14
#include <iostream>
#include <utility>
using namespace std;
int main()
{
int x = 10;
int y = 20;
exchange(x, y);
cout << "Value of x:" << x << '\n'
<< "Value of y:" << y << endl;
int a = 40;
int b = 30;
b = exchange(a, b);
cout << "Value of a:" << a << '\n'
<< "Value of b:" << b << endl;
return 0;
}
|
Output
Value of x:20
Value of y:20
Value of a:30
Value of b:40
Example 2:
C++14
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
int main()
{
vector< int > v1 = { 2, 4, 6, 8 };
vector< int > v2 = { 1, 3, 5, 7 };
v2 = exchange(v1, v2);
cout << "Values of v1 after exchange:" << endl;
for ( auto ele : v1) {
cout << ele << " " ;
}
cout << endl;
cout << "Values of v2 after exchange:" << endl;
for ( auto ele : v2) {
cout << ele << " " ;
}
return 0;
}
|
Output
Values of v1 after exchange:
1 3 5 7
Values of v2 after exchange:
2 4 6 8
Share your thoughts in the comments
Please Login to comment...