5.7.3. The Swapping Problem (2)

Time: 00:01:56 | Download: Large, LargeCC, Small | Streaming, Streaming (CC) | Slides (PDF)
Review

The initial swapping problem used a generalized data type, T, to introduce the operational pattern necessary to swap the contents of two variables. The pattern works for all fundamental types (i.e., programmers can replace T with an int, double, etc.). In the initial problem, two glasses of liquid represented two variables in a program. Directly pouring the liquid from one glass to the other would overflow the second glass, demonstrating the need for a third, temporary glass. The behavior of program variables isn't quite the same - the data in the "pouring" variable overwrites the data in the receiving variable - but the idea is similar: a variable can't simultaneously save two distinct values. Just as we needed a temporary glass to solve the problem with glasses and liquid, we also need a third, temporary variable to solve the swapping problem in a computer program. The second version of the swapping problem replaces T with a structure object.

#include <iostream>
#include <string>
using namespace std;

struct student
{
	int	id;
	string	name;
	double	gpa;
};

void print(student temp)
{
	cout << "ID:   " << temp.id << endl;
	cout << "Name: " << temp.name << endl;
	cout << "GPA:  " << temp.gpa << endl;
}

int main()
{
	student	s1 = { 123, "dilbert", 3.0 };
	student s2 = { 987, "alice", 4.0 };

	print(s1);
	print(s2);

	student temp = s2;
	s2 = s1;
	s1 = temp;

	print(s1);
	print(s2);

	return 0;
}
The swapping problem with structures. We can build a solution by bringing past examples together like puzzle pieces. The example highlights the swapping instructions. We'll see a more formal introduction to functions in the next chapter, but we must wait until chapter 8 for a more detailed presentation of strings.