# exchange() Function in C++ 14

• Difficulty Level : Basic
• 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.

1. The parameter needs to be set.
2. 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

 `// C++ Program to demonstrate``// exchange()``#include ``#include ``using` `namespace` `std;` `int` `main()``{``    ``int` `x = 10;``    ``int` `y = 20;` `    ``// Setting value of y to x``    ``exchange(x, y);` `    ``cout << ``"Value of x:"` `<< x << ``'\n'``         ``<< ``"Value of y:"` `<< y << endl;``    ``int` `a = 40;``    ``int` `b = 30;` `    ``// Setting value of b to a and copying a to b``    ``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

 `// C++ Program to demonstrate``// exchange()``#include ``#include ``#include ``using` `namespace` `std;` `int` `main()``{``    ``// We can also set one vector``    ``// values to another vector``    ``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 ```

My Personal Notes arrow_drop_up