forked from portfoliocourses/cplusplus-example-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswap_function.cpp
More file actions
71 lines (53 loc) · 1.82 KB
/
swap_function.cpp
File metadata and controls
71 lines (53 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*******************************************************************************
*
* Program: swap() Standard Library Function
*
* Description: Example of using the swap() function in the C++ standard library.
*
* YouTube Lesson: https://www.youtube.com/watch?v=TMVSRaKT3VU
*
* Author: Kevin Browne @ https://portfoliocourses.com
*
*******************************************************************************/
#include <iostream>
// we can access the swap() function by including utility
#include <utility>
using namespace std;
// A simple class
class Data
{
public:
int value;
};
int main()
{
int a = 2;
int b = 7;
// output a and b before the swap
cout << "a: " << a << " b: " << b << endl;
// we can use swap to swap primitive types like int values
swap(a,b);
// output a and by after the swap
cout << "a: " << a << " b: " << b << endl;
int x[] = {1,2,3};
int y[] = {4,5,6};
// output x[] and y[] array values before the swap
cout << "x[]: " << x[0] << "," << x[1] << "," << x[2] << endl;
cout << "y[]: " << y[0] << "," << y[1] << "," << y[2] << endl;
// we can also use swap to swap array values
swap(x,y);
// output x[] and y[] array values after the swap
cout << "x[]: " << x[0] << "," << x[1] << "," << x[2] << endl;
cout << "y[]: " << y[0] << "," << y[1] << "," << y[2] << endl;
// create two Data object instances and set the value member variable
Data dataX, dataY;
dataX.value = 2;
dataY.value = 7;
// output the value member variable values of dataX and dataY before the swap
cout << "X: " << dataX.value << " Y: " << dataY.value << endl;
// swap can also swap object instances
swap(dataX, dataY);
// output the value member variable values of dataX and dataY after the swap
cout << "X: " << dataX.value << " Y: " << dataY.value << endl;
return 0;
}