16

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 26

1. A palindrome is a string that is the same backward as it is forward.

For
example, tot
and otto are rather short palindromes. Write a program that lets a user enter a
string
and that passes to a bool function a reference to the string. The function should
return
true if the string is a palindrome and false otherwise. At this point, dont worry
about
complications such as capitalization, spaces, and punctuation. That is, this
simple version
should reject Otto and Madam, Im Adam. Feel free to scan the list of string
methods in Appendix F for methods to simplify the task.
cp16ex1.cpp
1 #include <iostream>
2 #include <string>
3
4 using namespace std;
5
6 bool ispalindrome(const string &); // function takes a string ref and returns true
if string is palindrome
7
8
9
1
0
1
1
1
2
1
3

int main()
{
string my;

cout << "Enter words (case and punctuation sensitive), q to quit: ";
while (cin >> my && my != "q") // enter words until q is entered
{
if (ispalindrome(my)) // check if entered word is palindrome

1
4

cout << my << " is palindrome!!\n";


else

1
5

cout << my << " is not palindrome!!\n";

1
6

1
7

cout << "\nThe end!";

1
8
1
9
2
0}

cin.get();
cin.get();
return 0;

2
1

bool ispalindrome(const string & st) // const & reference, we need original
2 string to compare with reversed version
2
{
2
string temp = st; // save original string to a temporary string
3
2
4
2
5
2
6
2
7
2
}
8
2
9
3
0
3
1
3
2
3
3
3
4
3
5
3
6
3

reverse(temp.begin(), temp.end()); // reverse the temporary


cout << "\nReversed: " << temp << endl; // display it

if (temp == st) // if reversed = original


return true; // then it is palindrome
else
return false; // otherwise, it is not

7
3
8

2. Do the same problem as given in Programming Exercise 1, but do worry about


complications
such as capitalization, spaces, and punctuation. That is, Madam, Im Adam
should test as a palindrome. For example, the testing function could reduce the
string to
madamimadam and then test whether the reverse is the same. Dont forget
the useful
cctype library. You might find an STL function or two useful although not
necessary.
cp16ex2.cpp
1 #include <iostream>
2 #include <string>
3 #include <cctype> // required for isalpha and tolower functions, although may
not be necessary under VS 2010
4
5
6

using namespace std;

7
8

bool ispalindrome(const string &); // function takes a string ref and returns true
if string is palindrome

9
1
int main()
0
{
1
1
string my;
1
2
1
3
1
4

cout << "Enter words (capitalization and punctuation ignored), q to quit: ";
while (getline(cin,my) && my != "q") // enter words until q is entered
{
if (ispalindrome(my)) // check if entered word is palindrome

1
5

cout << my << " is palindrome!!\n";


else

1
6
1

cout << my << " is not palindrome!!\n";


}

7
1
8
1
9
2
0

cout << "\nThe end!";

cin.get();
cin.get();
return 0;

2}
1
2
2 bool ispalindrome(const string & st) // const & reference, we need original
string to compare with reversed version
2
3{
string temp_orig = st; // save string value to temporary variable, thus
2
preserving
original passed string untouched
4
2
5

string temp_rev;

2
6

int j = 0;

2
7

//let's remove all non-alphabetic symbols from a string

for (int i = 0; i < st.size(); i++)

// loop through each character in a string

if (!isalpha(st[i])) // if non-alphabetic character is found (such as .!,'), do


2
8 not store it in a new string
2
9
3
0

continue;
else
{

temp_orig[j] = tolower(st[i]); // else, if character is alphabetic, convert


3
it to lowercase (to test for equality) and store
1
j++; // increase the index to place the next alphabetic character in
3
the same string being examined, no need to create an extra variable
2
}
3
3
}
3
temp_orig.resize(j); // reduce the string to j places, all proper alphabetic
4 character are stored from 0 to j indexes in a string being examined and edited
3
temp_rev = temp_orig; // store the reversed version of alpha-only string to
5 check for equality
3
6

reverse(temp_rev.begin(), temp_rev.end()); // do the reverse operation

3
7
3
8
3
9
4
0
4
1
4
2
4
3
4
4

cout << "\nReversed: " << temp_rev << endl; // display it

4
5

if (temp_rev == temp_orig) // if reversed = original

4
6

else

4
7}

return true; // then it is palindrome

return false; // otherwise, it is not

4
8
4
9
5
0
5
1
5
2
5
3
5
4

3. Redo Listing 16.3 so that it gets it words from a file. One approach is to use a
vector object instead of an array of string. Then you can use push_back() to

copy how ever many words are in your data file into the vector object and use
the size() member to determine the length of the word list. Because the program
should read one word at a time from the file, you should use the >> operator
rather than
getline(). The file itself should contain words separated by spaces, tabs, or new
lines.
cp16ex3.cpp
1 #include <iostream>
2 #include <fstream> // include fstream to read files
3 #include <string>
4 #include <cstdlib>
5 #include <ctime>
6 #include <cctype>
7 #include <vector> // include vector to contain array of words read from file
8
9 using namespace std;
10
11 int main()
12 {
13

std::srand(std::time(0));

14
15

ifstream fin; // ifstream object to read a file

16

string str_finput; // string buffer to read one word at a time from file

17

string filename; // filename to open

18

vector<string> words; // container to store words read from file

19
20

cout << "Enter filename with words to guess: "; // get the filename

21

(cin >> filename).get();

22
23

fin.open(filename); // open it

24

if (fin.fail())

25
26

cout << "Error opening file: " << filename << " not found!\n"; // if
invalid file name or not found - display the error
else

27

28

while(!fin.eof()) // reading from file until EOF is reached

29

30

fin >> str_finput; // read one word at a time

31
32

words.push_back(str_finput); // immediately store the word in vector


array
}

33
34
35
36

fin.close(); // close the file


}

37
if (words.size() > 0 && words.size() < 2 && words[0].length() < 2) // if file
was opened but did not contain any words (less than 2 chars in length, it is
39 error!
38

cout << "No words to guess or file is empty!\n"; // display error msg

40
41

else if (words.size() > 0 && words[0].length() > 2)

42

43
44
45
46
47
48
49
50

cout << "Total words loaded: " << words.size() << endl; // display total
# of words loaded to vector array
char play;
cout << "Will you play a word game? <y/n> ";
cin >> play;
play = tolower(play);
while (play == 'y')
{

string target = words[std::rand() % words.size()]; // get the random


51 word from vector array, same syntax as with regular array
52

int length = target.length(); // FOR THE REST OF COMMENTS FOR THIS


53 PROGRAM SEE THE TEXTBOOK :)
54

string attempt(length, '-');

55

string badchars;

56

int guesses = 6;

57

cout << "Guess my secret word. It has " << length

58

<< " letters, and you guess\n"

59

<< "one letter at a time. You get " << guesses

60

<< " wrong guesses.\n";

61

cout << "Your word: " << attempt << endl;

62

while (guesses > 0 && attempt != target)

63

64

char letter;

65

cout << "Guess a letter: ";

66

cin >> letter;

67
68
69

if (badchars.find(letter) != string::npos || attempt.find(letter) !=


string::npos)
{
cout << "You already guessed that. Try again.\n";

70

continue;

71
72
73
74
75

}
int loc = target.find(letter);
if (loc == string::npos)
{
cout << "Oh, bad guess!\n";

76

--guesses;

77

badchars += letter; // add to string

78
79
80
81
82
83
84
85
86
87

}
else
{
cout << "Good guess!\n";
attempt[loc]=letter;
// check if letter appears again
loc = target.find(letter, loc + 1);
while (loc != string::npos)
{
attempt[loc]=letter;

88

loc = target.find(letter, loc + 1);

89
90

91

92

cout << "Your word: " << attempt << endl;

93

if (attempt != target)

94

95

if (badchars.length() > 0)

96

cout << "Bad choices: " << badchars << endl;

97

cout << guesses << " bad guesses left\n";

98

99

10
0

if (guesses > 0)
cout << "That's right!\n";

10
1

else
cout << "Sorry, the word is " << target << ".\n";

10
2

cout << "Will you play another? <y/n> ";

10
3

cin >> play;


play = tolower(play);

10
4

10
5

10
6

cout << "Bye\n";

10
7

cin.get();

10
8

cin.get();

return 0;
}

10
9 list.txt

1
2
3
4
5
6
7
8
9
10

apiary
beetle
cereal
danger
ensign
florid
garage
health
insult
jackal
keeper
loaner

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

manage
nonce
onset
plaid
quilt
remote
stolid
train
useful
valid
whence
xenon
yearn
zippy

4. Write a function with an old-style interface that has this prototype:


int reduce(long ar[], int n);
The actual arguments should be the name of an array and the number of
elements in the
array. The function should sort an array, remove duplicate values, and return a
value
equal to the number of elements in the reduced array. Write the function using
STL
functions. (If you decide to use the general unique() function, note that it returns
the
end of the resulting range.) Test the function in a short program.
cp16ex4.cpp
1 #include <iostream>
2 #include <algorithm>
3 #include <ostream>
4
5 using namespace std;
6
7 const int NUM = 18; // number of elements in original array
8 int reduce(long [], int); // prototype of reduce function
9
1 int main()
0
{
1
long arr[NUM] = {1, 1, 2, 3, 45, 5, 4, 11, 45, 70, 9, 47, 48, 47, 73, 90, 11,
1

1 48};
2
1
3

int i = 0;

1
4

for (i = 0; i < NUM; i++) // display the contents of original array

1
5

cout << arr[i] << " ";

2
0

cout << arr[i] << " ";

int newNUM = reduce(arr, NUM); // reduce array and store the number of
1 new sequence elements into variable
6
cout << "\nNumber of elements in arr[] after reduce: " << newNUM <<
1 endl; // disp the info
7
cout << "Array after sort & duplicates removal: "; // display sorted & unique
1 original array
8
for (i = 0; i < newNUM; i++) // dupe values are still in array after newNUM
1 but not displayed, STL functions such as erase can be used with list or vector
9 list if needed

2
1

cin.get();
cin.get();

2
2

return 0;

2}
3
2
4 int reduce(long ar[], int n)
2{
5
2
6

return unique(ar, ar + n) - ar; // remove duplicate values and immediately


return the # of elements of the newly unique and sorted array

2
}
7
2
8
2
9
3
0
3

sort(ar, ar + n); // sort the array

1
3
2
3
3

5. Do the same problem as described in Programming Exercise 4, except make it


a template
function:
template
int reduce(T ar[], int n);
Test the function in a short program, using both a long instantiation and a string
instantiation.
cp16ex5.cpp
#include <iostream>
#include <algorithm>
#include <ostream>
#include <string>

using namespace std;

const int NUM = 18; // number of elements in original array


const int NUM2 = 9;

template <class T>


void display_array(T [], int n); // template used to display the contents of array T
with n elements

template <class T>


int reduce(T [], int n); // reduce template for array of type T with n elements

int main()
{
long arr[NUM] = {1, 1, 2, 3, 45, 5, 4, 11, 45, 70, 9, 47, 48, 47, 73, 90, 11,
48}; // array of long(S)
string city[NUM2] = {"new york", "washington", "philadelphia",

"new york", "miami", "washington",


"tampa", "los angeles", "miami"}; // array of strings

cout << "Arr array: ";


display_array(arr, NUM); // display contents of long array
cout << "\nCities array: ";
display_array(city, NUM2); // display contents of string array
int arrNewNum = reduce(arr, NUM); // reduce long array and get the
number of sorted & unique elements
int cityNewNum = reduce(city, NUM2); // same reduce for string array
cout << "\n\nArr after reduce: ";
display_array(arr, arrNewNum); // display newly sorted long array
cout << "Total unique Arr elements: " << arrNewNum; // display the
number of new sorted & unique elements
cout << "\n\nCities after reduce: ";
display_array(city, cityNewNum); // display newly sorted string array
cout << "Total unique City elements: " << cityNewNum; // display the
number of new sorted & unique elements

cin.get();
cin.get();
return 0;
}

template <class T>


int reduce(T ar[], int n)
{
sort(ar, ar + n); // sort the array
return unique(ar, ar + n) - ar; // remove duplicate values and immediately
return the # of elements of the newly unique and sorted array
}

template <class T>


void display_array(T ar[], int n)

{
for (int i = 0; i < n; i++) // go through every element of array
cout << ar[i] << " "; // and display its contents
cout << endl;
}

6.
Redo the example shown in Listing 12.15, using the STL queue template class instead of
the Queue class described in Chapter 12.
customer.h
1 #ifndef CUSTOMER_H_ // queue class is reduced to customer class only, since for this
2 #define CUSTOMER_H_ // programming exercise we'll use STL queue class instead of
our own Queue class from Chapter 12
3
// This queue will contain Customer items
4
class Customer
5
{
6
private:
7
long arrive; // arrival time for customer
8
int processtime; // processing time for customer
9
public:
1
0
Customer() { arrive = processtime = 0; }
11

void set(long when);

1
2

long when() const { return arrive; }


int ptime() const { return processtime; }

1
3 };
1
4

1
5
1
6
inline void Customer::set(long when)
1
7 {
processtime = std::rand() % 3 + 1;

1
8

arrive = when;
1
9 }
2
0
#endif
2
1
2
2
cp16ex6.cpp
1 #include <iostream>
2 #include <cstdlib> // for rand() and srand()
3 #include <ctime> // for time()
4 #include "customer.h" // include our Customer class without any former Queue class
elements from Chapter 12
5
#include <queue> // include queue<typename T> class from STL library for this exercise
6
7
typedef Customer Item; // customer Item class instance is declared here instead of former
8 Queue.h
// because we'll use STL queue class instead of our own Queue class from

9
Chapter 12
1
0

11const int MIN_PER_HR = 60;


1 bool newcustomer(double x); // is there a new customer?
2
1
3 int main()
1 {
4
using std::cin;
1
5
1
6

using std::cout;
using std::endl;
using std::ios_base;

1
7
1
8
1
9
2
0
2
1
2
2
2
3
2
4
2
5
2
6
2

// setting things up
std::srand(std::time(0)); // random initializing of rand()
cout << "Case Study: Bank of Heather Automatic Teller\n";
cout << "Enter maximum size of queue: ";
int qs;
cin >> qs; // line queue holds up to qs people
std::queue<Item> line; // declare the queue STL class variable - line, formerly Queue
line(qs);
cout << "Enter the number of simulation hours: ";
int hours; // hours of simulation
cin >> hours;
// simulation will run 1 cycle per minute
long cyclelimit = MIN_PER_HR * hours; // # of cycles
cout << "Enter the average number of customers per hour: ";
double perhour; // average # of arrival per hour
cin >> perhour;

double min_per_cust; // average time between arrivals

2
8

min_per_cust = MIN_PER_HR / perhour;


Item temp; // new customer data

2
9
3
0

long turnaways = 0; // turned away by full queue


long customers = 0; // joined the queue
long served = 0; // served during the simulation

3
1
3
2

long sum_line = 0; // cumulative line length


int wait_time = 0; // time until autoteller is free
long line_wait = 0; // cumulative time in line

3
3
3
4
3
5
3
6

// running the simulation


for (int cycle = 0; cycle < cyclelimit; cycle++)
{
if (newcustomer(min_per_cust)) // have newcomer
{

if (line.size() == qs) // check to see if queue is full, formerly "line.isfull()", STL


3 queue class doesn't have a method to set the size of queue or check if it's full
7
turnaways++;
3
8
else
3
9

{
customers++;

4
0

temp.set(cycle); // cycle = time of arrival

4
1
4
2

line.push(temp); // add newcomer to line, formerly "line.enqueue(temp);"


}
}

4
if (wait_time <= 0 && !line.empty()) // change from !line.isempty() to !line.empty() to
3 reflect new queue STL class

4
4

{
line.pop(); // attend next customer, formerly line.dequeue (temp);

4
5

wait_time = temp.ptime(); // for wait_time minutes

4
6

line_wait += cycle - temp.when();


served++;

4
7
4
8

}
if (wait_time > 0)
wait_time--;

4
9
5
0
5
1
5
2

sum_line += line.size();
}
// reporting results
if (customers > 0)
{
cout << "customers accepted: " << customers << endl;

5
3

cout << " customers served: " << served << endl;

5
4

cout << " turnaways: " << turnaways << endl;


cout << "average queue size: ";

5
5

cout.precision(2);

5
6

cout.setf(ios_base::fixed, ios_base::floatfield);
cout.setf(ios_base::showpoint);

5
7

cout << (double) sum_line / cyclelimit << endl;

5
8
5
9
6

cout << " average wait time: "


<< (double) line_wait / served << " minutes\n";
}

else

6
1

cout << "No customers!\n";

6
2

cout << "Done!\n";

6
3

cin.get();
cin.get();

6
4

return 0;

6 }
5
6
6 // x = average time, in minutes, between customers
6 // return value is true if customer shows up this minute
7
bool newcustomer(double x)
6
8 {
6
9
7
0
7
1
7
2
7
3
7
4
7
5
7

return (std::rand() * x / RAND_MAX < 1);


}

6
7
7
7
8
7
9
8
0
8
1
8
2
8
3
8
4
8
5
8
6
8
7
8
8
8
9
9
0
9
1
9

2
9
3
9
4
9
5
9
6

7. A common game is the lottery card. The card has numbered spots of which a certain
number are selected at random. Write a Lotto() function that takes two arguments. The
first should be the number of spots on a lottery card, and the second should be the
number of spots selected at random. The function should return a vector object
that contains, in sorted order, the numbers selected at random. For example, you could
use the function as follows:
vector winners;
winners = Lotto(51,6);
This would assign to winners a vector that contains six numbers selected randomly from
the range 1 through 51. Note that simply using rand() doesnt quite do the job because
it may produce duplicate values. Suggestion: Have the function create a vector that contains
all the possible values, use random_shuffle(), and then use the beginning of the
shuffled vector to obtain the values. Also write a short program that lets you test the
function.
cp16ex7.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

#include <iostream>
#include <vector>
// include vector for vector template
#include <algorithm>
// include algorithm header to use with sort,
random_shuffle, and find STL functions
using namespace std;
typedef vector<int> Ticket;
// Ticket is now vector<int> for ease
of use, holds lottery numbers (array)
Ticket Lotto(int, int);
// function returns vector<int> (or Ticket),
first int argument is a max range (from 1 to max range) to draw Lottery
numbers, and second int argument is how many spots or numbers to guess
to win the lotto
void DisplayTicket(const Ticket &); // display ticket or vector<int>
array

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

int main()
{
int lotMaxR, winN, matchingN = 0; // lotMaxR = max range number for
lottery numbers to be drawn, from 1 to lotMaxR
do
{
cout << "Enter lottery range, from 1 to (5 or greater): "; //
ask to input maximum range of possible lottery draw number
} while(cin >> lotMaxR && lotMaxR < 5); // get proper number from
user until 5 or more is entered
do
{
cout << "Enter how many numbers to draw (2 or greater): "; //
ask for how many spots on the lotto card or winning numbers to draw in
lottery play
} while(cin >> winN && winN < 2); // ask for input until 2 or
number is entered
Ticket winners = Lotto(lotMaxR,winN); // generate random numbers
for winning numbers
Ticket myticket = Lotto(lotMaxR,winN); // generate random numbers
for user's playing ticket, something like QuickPick
cout << "Winning numbers: ";
DisplayTicket(winners); // display winning numbers
cout << "Your ticket numbers: ";
DisplayTicket(myticket); // display playing user's numbers
cout << "Number(s) matched on your ticket: "; // display matching
numbers from both arrays (lottery drawn numbers and user's quick pick)
for (int i = 0; i < winN; i++)
if (find(winners.begin(), winners.end(), myticket[i]) !=
winners.end()) // compare each winning number to user's picked numbers
{
cout << myticket[i] << " "; // if matched, display the
number
matchingN++; // and increase the number of matched numbers
}
if (matchingN == 0) // if no numbers were matched display the
message
cout << "None" << endl;
else
cout << endl;
if (matchingN == winN && matchingN > 5) // if all winning numbers
guessed correctly and the total number of them is 6 or more - almost
impossible win, display epic congratulations message!
cout << "Oh my Flying Spaghetti Monster, you've guessed all
numbers!!! BEER IS ON ME!";
else if (matchingN == winN && matchingN == 2 ) // special occasion:
if out of 2 winning numbers 2 guessed correctly, display FREE ticket
prize msg
cout << "Congratulations, you've won min 2x2 game! Prize: 10
FREE tickets!" << endl;
else if (matchingN > 5) // display messages for each number of

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
10
0
10
1
10
2
10
3
10
4
10
5
10
6
10
7

correctly guessed numbers, the greater the number the more fun and
expensive prize....or maybe not :)
cout << "Congratulations, You've guessed " << matchingN << "
winning numbers!!! PRIZE: Skyscraper in New York City!" << endl;
else
switch(matchingN)
{
case 5:
cout << "Congratilations, You've guessed 5
winning numbers!!!! PRIZE: New Yacht filled with naked chicks!" << endl;
break;
case 4:
cout << "Congratulations, You've guessed 4
winning numbers!! PRIZE: Vacation to Siberian Gulag! :P" << endl;
break;
case 3:
cout << "Congratulations, You've guessed 3
winning numbers!! PRIZE: Bubble Gum that sticks to your shoes!" << endl;
break;
default:
cout << "You've guessed " << matchingN << "
winning number(s)!! Buy more tickets next time. Good luck!" << endl;
break;
}
cout << "\nBye!"; // all is done, good bye
cin.get();
cin.get();
return 0;
}
Ticket Lotto(int Tot, int Ran) // generate and return randomized & sorted
array of lottery numbers
{
Ticket temp; // create a ticket that will be returned once generated
with random lottery numbers with respect to arguments passed to function
int i = 0;
if (Tot < 5) // check for the first argument passed to function
{
cout << "Invalid number range, resetting to default: [1-5]" <<
endl; // if range of lottery number max is below 5, change it to min
allowed - 5
Tot = 5;
}
if (Ran < 2) // check the second argument, if less than 2, set it to
default value of 2, we need at least 2 winning numbers to play with
{
cout << "Invalid ticket request, setting number of winning
numbers to default - 2." << endl;
Ran = 2;
}
for (i = 0; i < Tot; i++) // generate non-random sequence of numbers
from 1 to Tot and store it in vector<int> array
temp.push_back(i+1);
for (i = 0; i < Ran; i++) // shuffle the numbers "Ran" many times to
have better randomization of numbers

random_shuffle(temp.begin(), temp.end());
temp.erase(temp.begin()+Ran, temp.end()); // erase unnecessary
numbers from Ran+, numbers from 1 to Ran are kept in.
sort(temp.begin(), temp.end()); // finally, sort the numbers

10
return temp; // and return the sorted and randomized array
8 }
10
9 void DisplayTicket(const Ticket & t) // function displays victor<int>
110 array or defined as Ticket
{

for (int i = 0; i < t.size(); i++) // go through each element


until t.size(), the max number of elements, is reached
cout << t[i] << " "; // display the element
cout << endl;
}

8. Mat and Pat want to invite their friends to a party. They ask you to write a
program that
does the following:
Allows Mat to enter a list of his friends names. The names are stored in a
container
and then displayed in sorted order.
Allows Pat to enter a list of her friends names. The names are stored in a
second
container and then displayed in sorted order.
Creates a third container that merges the two lists, eliminates duplicates, and
displays
the contents of this container.
cp16ex8.cpp
1 #include <iostream>
2 #include <set>
3 #include <string>
4 #include <iterator>
5 #include <algorithm>
6
7
8 using namespace std; // I don't like typing std:: all the time
9
1 int main()
0
{
1
string input; // keyboard input string
1
ostream_iterator<string, char> out(cout, "\n"); // output iterator to display
1

2 container elements
1
3

set<string> mats_friends; // container set to hold list of Mat's friends

1
9

set<string> pats_friends; // Pat's friend container set

2
0

while (getline(cin,input) && input != "s") // get friends for Pat

// set - is used because it automatically sorts the elements


1 and allows only unique items in it
4
cout << "Enter guest list for Mat (s to stop): \n";
1
while (getline(cin,input) && input != "s") // enter friends until "s" is entered
5
for the name
1
mats_friends.insert(input);
// store a friend in container set
6
cout << "Mat's friends list: " << endl;
1
7
copy(mats_friends.begin(), mats_friends.end(), out); // display entered
friends for Mat by using iterator out
1
8

2
1

cout << "\nEnter guest list for Pat (s to stop): \n";

pats_friends.insert(input);

// store them in Pat's container set

cout << "Pat's friends list: " << endl;

2
copy(pats_friends.begin(), pats_friends.end(), out);
2 friends

// and display Pat's

2
3

set<string>comb_friends; // this set holds both unique and sorted list of


2 Mat's and Pat's friends
4
set_union(mats_friends.begin(), mats_friends.end(), pats_friends.begin(),
2 pats_friends.end(), insert_iterator<set<string> >(comb_friends,
5 comb_friends.begin())); // copy mat's and pat's friends into comb_friends set
2
cout << "\nPat's and Mat's friends who are welcome to Party: \n"; // set
6 automatically sorts & removes duplicate values
2
copy(comb_friends.begin(), comb_friends.end(), out); // display the final
7 merged, sorted, and unique list of friends of Mat and Pat
2
8
2
9
3
0
3
1

cin.get();
cin.get();
return 0;

3
2
3
3
3
4
3
5
3
6
3
7

You might also like