We have studied the swapping problem twice before, but this time, we have a sufficient understanding to change the problem fundamentally. Our previous explorations used the swapping problem as a lens to focus our attention on programming concepts and constructs. But swapping the values in a pair of variables is a real problem with real applications. With the following example, we develop an authentic solution to the swapping problem by creating a swap function.
Our first step is determining how to pass the data into the function. We have three passing techniques at our disposal:
int main() { student s1 = { 123, "dilbert", 3.0 }; student s2 = { 987, "alice", 4.0 }; print(s1); print(s2); swap(s1, s2); print(s1); print(s2); return 0; } |
void swap(student& param1, student& param2) { student temp = param2; //student& temp = param2; // doesn't work!! param2 = param1; param1 = temp; } |
(a) | (b) |
(c - student temp) | (d - student& temp) |
int main() { student s1 = { 123, "dilbert", 3.0 }; student s2 = { 987, "alice", 4.0 }; print(s1); print(s2); swap(&s1, &s2); print(s1); print(s2); return 0; } |
void swap(student* param1, student* param2) { student temp = *param2; *param2 = *param1; *param1 = temp; } |
(a) | (b) |
int main() { student* s1 = new student { 123, "dilbert", 3.0 }; student* s2 = new student { 987, "alice", 4.0 }; print(s1); print(s2); swap(s1, s2); print(*s1); print(*s2); return 0; } |
void print(student* temp) { cout << "ID: " << temp->id << endl; cout << "Name: " << temp->name << endl; cout << "GPA: " << temp->gpa << endl; } |
(a) | (b) |