Skip to content
Exercise · Final Project · lesson 2 of 3

Exercise: book catalog

Write the class Catalog, a library catalog; add the fields yourself. The file already defines the Book struct: the number id, the title, the author and lent, whether the book is lent out. void add(Book book) adds a book, and std::vector<Book> by_author(std::string_view author) const returns the author's books in the order they were added. bool lend(int id) lends a book out and returns true, and bool give_back(int id) takes it back and also returns true.

  • after add({5, "Persuasion", "Austen"}), add({2, "Dune", "Herbert"}) and add({3, "Emma", "Austen"}): by_author("Austen") → the books Persuasion and Emma, in that order
  • lend(2) → true, a second lend(2) → false
  • then give_back(2) → true, a second give_back(2) → false

Constraints: book numbers are unique, and for an author with no books by_author returns an empty vector. lend refuses if there is no book numbered id or it is already lent out. give_back refuses if there is no such book or it is not lent out. A method that refuses returns false and changes nothing.

catalog.cpp — cpp
cpp · 29 lines
Ctrl+Enter run · Esc leave editor