#include <cstdlib>
#include <string>
#include <iostream>
using namespace std;
void swap(string& str1, string& str2);
/******
signature: main: void -> int
purpose: demonstrate/test the function swap
examples: when this is run, I hope it prints:
FIRST: last_name: Bob
first_name: Bobby
AFTER call to swap(last_name, first_name):
last_name: Bobby
first_name: Bob
by: Sharon Tuttle
last modified 2016-12-08
*****/
int main()
{
string last_name = "Bob";
string first_name = "Bobby";
cout << "FIRST: last_name: " << last_name << endl;
cout << " first_name: " << first_name << endl;
cout << endl;
swap(last_name, first_name);
cout << "AFTER call to swap(last_name, first_name):" << endl;
cout << endl;
cout << " last_name: " << last_name << endl;
cout << " first_name: " << first_name << endl;
return EXIT_SUCCESS;
}
/******
signature: string& string& -> void
purpose: expects two string variables oor
things I CAN CHANGE, and returns nothing,
BUT has the SIDE EFFECT of making the 1st
argument's value the original value of the
2nd argument, and vice versa
examples:
string last_name = "Bob";
string first_name = "Bobby";
then if I run:
swap(last_name, first_name);
...then afterwards,
last_name == "Bobby"
first_name == "Bob"
and what if I now had:
string mid_init = "B";
swap(mid_init, first_name);
...then afterwards:
mid_init == "Bob"
first_name == "B"
*****/
void swap(string& str1, string& str2)
{
string temp;
// SAVE a copy of str1's value
temp = str1;
// now it is safe to overwrite str1
str1 = str2;
// now it is safe to overwrite str2
str2 = temp;
}