/////////////////////////////////////////////// // Library holdings // // Roger Hartley, Fall 1996 // // (modified for vectors, Spring 1997 // /////////////////////////////////////////////// #include #include #include #include // a book consists of a title and author class Book { private: string title; string author; public: Book() { title = author = ""; } Book(string t, string a) { title = t; author = a; } bool operator==(Book b) { return title == b.title && author == b.author; } string getTitle() { return title; } string getAuthor() { return author; } }; // a library is a number of books, stored in a vector class Library { private: vector collection; int number; public: Library() : collection(10) { number = 0; } void Add(Book b); void Delete(Book b); void PrintHoldings(); }; // collection is the application class, it contains // a library class Collection { private: Library lib; public: void run(); }; // adding a book to the collection increases the number held by one void Library::Add(Book b) { collection[number++] = b; } // deleting a book is a search through the vector // if the book is found, it is deleted and the number held // decreased by one void Library::Delete(Book b) { for (int n = 0; n < number; n++) if (collection[n] == b) { for (int nn = n + 1; nn < number; nn++) collection[nn - 1] = collection[nn]; cout << b.getTitle() << " by " << b.getAuthor() << " deleted" << endl; --number; return; } cout << b.getTitle() << " not found" << endl; } // printing the library is a single pass through // the elements of the vector void Library::PrintHoldings() { cout << endl << "There are " << number << " books" << endl; for (int n = 0; n < number; n++) cout << setw(12) << collection[n].getTitle() << setw(6) << " by " << collection[n].getAuthor() << endl; } // books are added to the library from title and author // typed in by the user void Collection::run() { Library lib; string title, author; cout << "Type title and author, separated by a space: "; cin >> title >> author; while (!cin.eof()) { lib.Add(Book(title, author)); cout << "Type title and author, separated by a space: "; cin >> title >> author; } lib.PrintHoldings(); // print the library holdings lib.Delete(Book("Relativity", "Einstein")); // delete if present lib.Delete(Book("MyLife", "Hartley")); // delete if present lib.PrintHoldings(); // print holdings again to verify deletions } // the main function just calls the run function of the application int main() { Collection c; c.run(); }