Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

lafore_robert_objectoriented_programming_in_c

.pdf
Скачиваний:
51
Добавлен:
27.03.2023
Размер:
8.94 Mб
Скачать

8.c

9.fixed data type, any data type

10.store data

11.c

12.try, catch, and throw

13.throw BoundsError();

14.false; they must be part of a try block

15.d

16.

class X

{

public:

int xnumber; char xname[MAX];

X(int xd, char* xs)

{

xnumber = xd; strcpy(xname, xs);

}

};

17.false

18.a and d

19.d

20.true

21.independent, dependent

22.a

23.false

24.additional information

Answers to Questions and Exercises

965

G

Q

E UESTIONS ANSWERS

TOANDXERCISES

Solutions to Exercises

1.

//ex14_1.cpp

//template used for function that averages array #include <iostream>

using namespace std;

Appendix G

966

////////////////////////////////////////////////////////////////

template <class atype>

//function template

atype avg(atype* array, int size)

 

{

 

atype total = 0;

 

for(int j=0; j<size; j++)

//average the array

total += array[j];

 

return (atype)total/size;

 

}

 

////////////////////////////////////////////////////////////////

int intArray[] =

{1, 3, 5,

9, 11, 13};

long longArray[] =

{1, 3, 5,

9, 11, 13};

double doubleArray[] = {1.0, 3.0, 5.0, 9.0, 11.0, 13.0};

char charArray[] =

{1, 3, 5,

9, 11, 13};

int main()

 

 

 

{

 

 

 

cout <<

“\navg(intArray)=” <<

avg(intArray, 6);

cout <<

“\navg(longArray)=” << avg(longArray, 6);

cout <<

“\navg(doubleArray)=”

<< avg(doubleArray, 6);

cout <<

“\navg(charArray)=” << (int)avg(charArray, 6) << endl;

return 0;

}

2.

//ex14_2.cpp

//implements queue class as a template #include <iostream>

using namespace std; const int MAX = 3;

////////////////////////////////////////////////////////////////

template <class Type> class Queue

{

private:

 

 

Type qu[MAX];

//array of any type

int head;

//index of start of queue (remove item here)

int tail;

//index of end of queue (insert item here)

public:

 

 

Queue()

 

//constructor

{ head = -1; tail = -1; }

void put(Type

var)

//insert item at queue tail

{

 

 

qu[++tail]

= var;

 

if(tail >=MAX-1)

//wrap around if past array end

tail = -1;

 

Answers to Questions and Exercises

967

}

 

Type get()

//remove item from queue head

{

 

Type temp = qu[++head];

//store item

if(head >= MAX-1)

//wrap around if past array end

head = -1;

 

return temp;

//return item

}

 

};

 

////////////////////////////////////////////////////////////////

int main()

 

 

 

{

 

 

 

Queue<float> q1;

//q1 is

object of class Queue<float>

q1.put(1111.1F);

 

 

//put 3

q1.put(2222.2F);

 

 

 

q1.put(3333.3F);

 

 

 

cout << “1: “ << q1.get() <<

endl;

//get 2

cout << “2: “ << q1.get() <<

endl;

 

q1.put(4444.4F);

 

 

//put 2

q1.put(5555.5F);

 

 

 

cout << “3: “ << q1.get() <<

endl;

//get 1

q1.put(6666.6F);

 

 

//put 1

cout << “4: “ << q1.get() <<

endl;

//get 3

cout << “5: “ << q1.get() <<

endl;

 

cout << “6: “ << q1.get() <<

endl;

 

Queue<long> q2;

//q2 is

object of class Queue<long>

q2.put(123123123L);

//put 3

longs, get 3 longs

q2.put(234234234L);

 

 

 

q2.put(345345345L);

 

 

 

cout << “1: “ << q2.get() <<

endl;

 

cout << “2: “ << q2.get() <<

endl;

 

cout << “3: “ << q2.get() <<

endl;

 

return 0;

 

 

 

}

 

 

 

3.

//ex14_3.cpp

//implements queue class as a template

//uses exceptions to handle errors in queue #include <iostream>

using namespace std; const int MAX = 3;

G

Q E UESTIONS ANSWERS XERCISES AND TO

Appendix G

968

////////////////////////////////////////////////////////////////

template <class Type>

 

 

class Queue

 

 

 

{

 

 

 

private:

 

 

 

Type qu[MAX];

//array of any type

int head;

//index of front of queue (remove old item)

int tail;

//index of back of queue (insert new item)

int count;

//number of items in queue

public:

 

 

 

class full {

};

//exception classes

class empty

{ };

 

 

//--------------------------------------------------------------

 

 

 

Queue()

 

//constructor

{ head = -1; tail = -1;

count = 0; }

void put(Type var)

//insert item at queue tail

{

 

 

 

if(count >= MAX)

//if queue already full,

throw full();

//

throw exception

qu[++tail] = var;

//store item

++count;

 

 

 

if(tail >=MAX-1)

//wrap around if past array end

tail = -1;

 

 

}

 

 

 

//--------------------------------------------------------------

 

 

 

Type get()

 

//remove item from queue head

{

 

 

 

if(count <= 0)

//if queue empty,

throw empty();

//

throw exception

Type temp = qu[++head]; //get item

--count;

 

 

 

if(head >= MAX-1)

//wrap around if past array end

head = -1;

 

 

return temp;

//return item

}

 

 

 

};

 

 

 

////////////////////////////////////////////////////////////////

int main()

 

{

 

Queue<float> q1;

//q1 is object of class Queue<float>

float data;

//data item obtained from user

char choice = ‘p’;

//’x’, ‘p’ or ‘g’

do

//do loop (enter ‘x’ to quit)

{

 

Answers to Questions and Exercises

969

try

//try block

{

cout << “\nEnter ‘x’ to exit, ‘p’ for put, ‘g’ for get: “; cin >> choice;

if(choice==’p’)

{

cout << “Enter data value: “; cin >> data;

q1.put(data);

}

if(choice==’g’)

cout << “Data=” << q1.get() << endl; } //end try

catch(Queue<float>::full)

{

cout << “Error: queue is full.” << endl;

}

catch(Queue<float>::empty)

{

cout << “Error: queue is empty.” << endl;

}

} while(choice != ‘x’); return 0;

}//end main()

Chapter 15

Answers to Questions

1.a, b, d

2.vector, list, deque

3.set, map

4.a

5.true

6.c

7.false

8.iterator

9.a function object

10.c

11.false; it simply returns its value

12.3, 11

G

Q E UESTIONS ANSWERS XERCISES AND TO

Appendix G

970

13.duplicate

14.b, c

15.points to

16.false

17.bidirectional

18.*iter++

19.d

20.c

21.true

22.iterators

23.it’s a string used to separate the printed values

24.b

25.the elements will be ordered

26.true

27.pairs (or associations)

28.false

29.a, d

30.constructor

Solutions to Exercises

1.

//ex15_1.cpp

//type float stored in array, sorted by sort() #include <iostream>

#include <algorithm> using namespace std;

int main()

{

int j=0, k; char ch;

float fpn, farr[100];

do {

cout << “Enter a floating point number: “; cin >> fpn;

farr[j++] = fpn;

Answers to Questions and Exercises

971

cout

<< “Enter another (‘y’ or ‘n’): “;

cin >> ch;

} while(ch == ‘y’);

sort(farr, farr+j);

for(k=0; k<j; k++)

cout

<< farr[k] << “, “;

cout <<

endl;

return

0;

}

 

2.

//ex15_2.cpp

//vector used with string objects, push_back(), and [] #include <iostream>

#include <string>

#pragma warning (disable:4786) //Microsoft only #include <vector>

#include <algorithm> using namespace std;

int main()

{

vector<string> vectStrings; string word;

char ch;

do {

cout << “Enter a word: “; cin >> word; vectStrings.push_back(word);

cout << “Enter another (‘y’ or ‘n’): “; cin >> ch;

} while(ch == ‘y’);

sort( vectStrings.begin(), vectStrings.end() ); for(int k=0; k<vectStrings.size(); k++)

cout << vectStrings[k] << endl; return 0;

}

3.

//ex15_3.cpp

//home-made reverse() algorithm reverses a list #include <iostream>

#include <list> using namespace std;

G

Q E UESTIONS ANSWERS XERCISES AND TO

Appendix G

972

int main()

{

int j;

list<int> theList; list<int>::iterator iter1; list<int>::iterator iter2;

for(j=2; j<16; j+=2)

//fill list with 2, 4, 6, ...

theList.push_back(j);

 

cout << “Before reversal: “;

//display list

for(iter1=theList.begin(); iter1 != theList.end(); iter1++)

cout << *iter1 << “ “;

 

iter1 = theList.begin();

//set to first element

iter2 = theList.end();

//set to one-past-last

--iter2;

//move to last

while(iter1 != iter2)

 

{

 

swap(*iter1, *iter2);

//swap front and back

++iter1;

//increment front

if(iter1==iter2)

//if even number of elements

break;

 

--iter2;

//decrement back

}

 

cout << “\nAfter reversal: “; //display list for(iter1=theList.begin(); iter1 != theList.end(); iter1++)

cout << *iter1 << “ “; cout << endl;

return 0;

}

4.

//ex15_4.cpp

//a multiset automatically sorts person objects stored by pointer #include <iostream>

#include <set>

#pragma warning (disable:4786) #include <string>

using namespace std;

class person

{

Answers to Questions and Exercises

973

private:

string lastName; string firstName; long phoneNumber;

public:

person() : // default constructor lastName(“blank”), firstName(“blank”), phoneNumber(0L)

{}

// 3-arg constructor person(string lana, string fina, long pho) :

lastName(lana), firstName(fina), phoneNumber(pho)

{}

friend bool operator<(const person&, const person&);

void display() const // display person’s data

{

cout << endl << lastName << “,\t” << firstName << “\t\tPhone: “ << phoneNumber;

}

long get_phone() const // return phone number { return phoneNumber; }

}; //end class person //--------------------------------------------------------------

// overloaded < for person class

bool operator<(const person& p1, const person& p2)

{

if(p1.lastName == p2.lastName)

return (p1.firstName < p2.firstName) ? true : false; return (p1.lastName < p2.lastName) ? true : false;

}

//--------------------------------------------------------------

// function object to compare persons using pointers class comparePersons

{

public:

bool operator() (const person* ptrP1,

const person* ptrP2) const { return *ptrP1 < *ptrP2; }

};

////////////////////////////////////////////////////////////////

int main()

 

{

// a multiset of ptrs to persons

multiset<person*, comparePersons> setPtrsPers; multiset<person*, comparePersons>::iterator iter;

G

Q E UESTIONS ANSWERS XERCISES AND TO

Appendix G

974

//make persons

person* ptrP1 = new person(“KuangThu”, “Bruce”, 4157300); person* ptrP2 = new person(“McDonald”, “Stacey”, 3327563); person* ptrP3 = new person(“Deauville”, “William”, 8435150); person* ptrP4 = new person(“Wellington”, “John”, 9207404); person* ptrP5 = new person(“Bartoski”, “Peter”, 6946473); person* ptrP6 = new person(“McDonald”, “Amanda”, 8435150); person* ptrP7 = new person(“Fredericks”, “Roger”, 7049982); person* ptrP8 = new person(“McDonald”, “Stacey”, 7764987);

setPtrsPers.insert(ptrP1);

//put persons in multiset

setPtrsPers.insert(ptrP2);

 

setPtrsPers.insert(ptrP3);

 

setPtrsPers.insert(ptrP4);

 

setPtrsPers.insert(ptrP5);

 

setPtrsPers.insert(ptrP6);

 

setPtrsPers.insert(ptrP7);

 

setPtrsPers.insert(ptrP8);

 

//display multiset cout << “\n\nSet sorted when created:”;

for(iter=setPtrsPers.begin(); iter != setPtrsPers.end(); iter++ ) (**iter).display();

iter

=

setPtrsPers.begin();

//delete all persons

while(

iter != setPtrsPers.end() )

 

{

 

 

 

delete *iter;

//delete person

setPtrsPers.erase(iter++);

//remove pointer

}

 

 

 

cout

<< endl;

 

return

0;

 

}// end main()

Chapter 16

Answers to Questions

1.false

2.c, d

3.task

4.true

5.columns

6.a, c