Skip to content
Tutorials Center
My learning

Topics

Lesson 155 of 171 ยท Projects

Project: Library Catalog

Build a C++ library catalog in four stages - store books in a std::map, parse commands from input, search and sort with ranges, and manage loans with clear rules.

A small library catalog has everything that makes data-handling programs interesting. Each book has several fields. Books need stable identifiers that survive deletions. Librarians want to search by fragments of a title or author, sort the shelf list in different ways, and lend books out under rules ("at most three loans per member"). In this project you'll build such a catalog, driven by commands typed into the Input box.

You'll build it in four stages: a Book struct and a Catalog class, a command processor with input validation, searching and sorting with ranges, and finally loans and statistics. Each stage is a complete, runnable program that contains everything written so far, because each run starts fresh. The books are invented for this project, so any resemblance to a title on your shelf is a coincidence.

You'll practice structs and designated initializers, classes, std::map, std::vector, std::string_view, string methods, exceptions, lambdas and ranges and views.

Stage 1: books and a catalog

Two questions come first. What is a book, and how do we find one again?

A Book is plain data: an id, title, author, year and number of copies. There are no rules that tie these fields together yet, so a struct with public members is the honest choice. (Wrapping every field in a getter and setter would add code without protecting anything.)

Identity is the more interesting decision. You might be tempted to keep books in a std::vector<Book> and use the position as the id. That breaks as soon as a book is removed: every book after it shifts down, and "book 7" suddenly means a different book. Instead, the catalog hands out an id that never changes and stores books in a std::map<int, Book> keyed by it. A map gives:

  • lookup by id in O(log n), with a clear "not found" result,
  • iteration in id order (the order books were added), which makes listings predictable,
  • no shifting when entries are erased.

The Catalog class owns the map. Its job is to make sure every book in it is valid, so add is the only way to put a book in, and it checks the fields first. That's the difference between Book (a struct, no invariants) and Catalog (a class with private data and rules).

C++ Stage 1: a Book struct and a Catalog class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

A few details:

  • Designated initializers (C++20) like .title = std::move(title) name each field, so you can't accidentally swap the title and the author, both of which are strings. They must appear in declaration order.
  • add takes std::string by value and moves into the book. A caller passing a temporary or a string literal pays for one string construction, not two (see Parameters).
  • books() returns a const reference to the map. Callers can read and iterate, but can't insert books that skip validation.
  • The year check rejects obvious typos: printing with movable type in Europe started around 1450, and 2100 leaves room for advance copies. Plausibility checks like this catch a surprising number of data-entry mistakes.

Stage 2: commands from the Input box

A catalog that only knows its hard-coded books isn't much use. Stage 2 reads commands, one per line:

TEXT
add Title | Author | Year | Copies
list
show <id>

Choosing a format. Titles and authors contain spaces, so "split on spaces" can't tell where the title ends. A separator that rarely appears in titles solves it, and | is a common choice. The command word comes first, separated by a space, and the rest of the line is the argument. Fields are trimmed, so add Rivers Under Ash |Tomas Reyher| 1987 works as well as a tidy line. Being generous with whitespace and strict with content is a good default for anything humans type.

Errors are exceptions, handled in one place. Every helper (parse_int, Catalog::add, Catalog::get) throws when something is wrong, with a message a person can act on. The main loop wraps each command in try/catch, prints the message, and moves on to the next line. The helpers don't need to know they're being driven by text commands, which keeps them reusable.

Strict number parsing. parse_int uses std::from_chars and insists that the whole field is consumed, so 19x7 is an error rather than 19 (see Converting Between Strings and Numbers).

Duplicates. Adding the same title by the same author twice is almost certainly a mistake (to add copies you'd change the copy count). add compares case-insensitively, because "rivers under ash" and "Rivers Under Ash" are the same book to a human.

C++ Stage 2: a command processor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Every line of input produces either a result or exactly one error line, and the catalog only ever contains valid books. Look at the fourth add: it's rejected as "already in the catalog as #2" even though the letter case differs. The sixth add has only two fields and gets the usage message.

Two decisions deserve a closer look.

std::views::split keeps empty fields. Splitting "a||b" on | gives three fields, the middle one empty. That's what we want here: an empty title should be reported as "title and author are required", not silently skipped. (In the grade book project we skipped empty pieces, because there they came from repeated spaces. Same tool, different rule, because the formats differ.)

std::views::values turns a range of pair<const int, Book> into a range of Book. It's a view, so nothing is copied; the loop sees the books stored in the map.

Stage 3: searching and sorting with ranges

Librarians rarely know an exact title. Stage 3 adds:

TEXT
find <text>                   titles or authors containing the text, any case
list [id|title|author|year]   the shelf list in different orders
authors                       every author and how many books they have

Searching is filtering. Catalog::search builds a pipeline: take the map's values, keep the books whose lowercase title or author contains the lowercase search text (std::string::contains is C++23), turn each book into a pointer, and collect the pointers into a vector with std::ranges::to. The result holds const Book*, not copies. The books stay in the map; the vector is just a list of references to them. That's cheap, and it reflects the truth: a search result points at books, it doesn't create new ones.

Sorting pointers, with projections. sorted_by collects pointers to every book and sorts them with std::ranges::sort and a projection, a function that extracts the sort key from each element. Three details matter:

  • The title projection returns const std::string&. Without the explicit return type, a lambda returns std::string by value, and every comparison during the sort would copy two strings.
  • To sort by author and then year, the projection returns std::tie(b->author, b->year), a tuple of references. Tuples compare element by element, so books by the same author come out oldest first (see std::pair and std::tuple).
  • Sorting pointers leaves the map untouched, so the shelf order of list id never changes, no matter how often someone sorts by title.

Pointers into a std::map stay valid until that element is erased, even when other elements are inserted. That's a guarantee std::vector doesn't give you, and it's another reason the catalog uses a map.

Counting authors. authors builds a fresh std::map<std::string, int> and increments a counter for each book's author. operator[] inserts a zero the first time it sees a key, which is exactly right for counting.

C++ Stage 3: find, sort and count

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The add commands now run quietly (the program doesn't echo them), so the output starts with the searches. find moon finds "A Field Guide to Small Moons", find VALCOURT finds both of Ines Valcourt's books despite the capitals, and find dragons reports zero matches instead of an error, because an empty result is a perfectly good answer to a search. list author groups each author's books in year order, thanks to the tuple projection.

The search lowercases every title and author on every search, which allocates strings. For a few thousand books that's still instant. For a large catalog you'd store a lowercase copy of each searchable field when the book is added, or build an index (a map from each word to the books containing it). Measure first; then optimize the part that's actually slow (see Writing Fast C++).

std::tolower works one byte at a time and only knows the C locale, so it lowercases Aโ€“Z but leaves accented capitals such as "ร‰" alone. Correct case-insensitive matching for all languages needs a Unicode library such as ICU. For an English catalog, ASCII lowercasing is a reasonable, clearly documented limitation.

Stage 4: loans and statistics

The final stage lets members borrow and return books:

TEXT
borrow <id> <member>
return <id> <member>
loans
stats

Loans come with rules, and each rule becomes a check that throws a LoanError before anything changes:

  1. A book can't be lent if all its copies are out.
  2. A member can't borrow the same book twice at once.
  3. A member can hold at most three books.
  4. Only a member who borrowed a book can return it.

Where loans live. Each Book gets a std::vector<std::string> borrowers, and the number of available copies is computed from it: copies - borrowers.size(). There's deliberately no separate "available" counter. Two numbers that must agree will eventually disagree, after a bug or a missed update. One source of truth can't contradict itself. The same thinking applies to "how many books does this member have?": loans_of counts by scanning the catalog instead of keeping a second map in sync. For a few thousand books the scan is fast. If it ever got slow, you'd add an index and update it in the same two functions that change loans, borrow and give_back (return is a keyword, so it can't be a function name).

A custom exception type. LoanError derives from std::runtime_error. It isn't strictly necessary here, since the loop prints every exception the same way, but it documents that these failures are rule violations, not bad input, and it would let a future GUI show them differently (see Custom Exception Classes).

Private mutable access. borrow needs to modify a book, but the public get returns const Book& so outside code can't edit borrowers and bypass the rules. The class therefore has a private find_book that returns Book&. The public interface stays read-only; only the catalog's own member functions can change books.

Statistics with algorithms. stats uses std::ranges::minmax_element with the projection &Book::year to find the oldest and newest book in one pass, std::ranges::fold_left (C++23) to total the copies, and a std::map<int, int> keyed by decade (year / 10 * 10) to draw a small chart. Because the decade map is sorted, the chart comes out in chronological order without any extra work. One small surprise: minmax_element returns iterators into the views::values view, and those iterators support * but not ->, so the code dereferences them into const Book& references first.

Designated initializers and new members. Adding borrowers to Book made GCC warn (-Wmissing-field-initializers, part of -Wextra) that the designated initializer in add leaves it out. The member would be empty anyway, but add now writes .borrowers = {} to say so explicitly and keep the build warning-free.

C++ Stage 4: the complete catalog with loans

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Follow the loans in the output. All three copies of the moons guide go to ana, ben and chen, so dev is turned away. Ana then borrows two more books, which brings her to the limit of three, so her request for a fourth is refused. Her attempt to borrow the cartographer again is refused as a duplicate, and she can't return a book she never borrowed. Once ben returns his copy, dev gets it. The loans report groups loans by member, sorted by name because the temporary map is sorted.

A subtle point: split_fields(argument, ' ')

The borrow command reuses split_fields with a space separator. Because split keeps empty pieces, borrow 3 ana (two spaces) produces three fields, one of them empty, and gets the usage message. That's strict but predictable. If you want to be generous, filter out empty fields for this command, the way the grade book project did.

Why loans_of takes std::string_view

loans_of only reads the member name, so std::string_view lets callers pass a std::string, a literal or a slice of a line without creating a string. std::ranges::contains(book.borrowers, member) compares each std::string with the view directly. borrow takes const std::string& instead, because it stores the name in borrowers and needs an owned string anyway (see std::string_view).

Ideas to extend it

  • Remove books. Add remove <id>, refusing while any copy is on loan. Then confirm the earlier claim: ids of the other books don't change, and pointers held in search results stay valid for books that weren't removed.
  • Due dates. Store a due date with each loan using std::chrono::year_month_day and add an overdue <date> command (see Dates, Times and Durations with chrono).
  • A word index. Build std::unordered_map<std::string, std::vector<int>> from each lowercase title word to book ids, and make find use it for single-word searches.
  • Reservations. When all copies are out, let a member join a waiting list (a std::queue<std::string> per book) and give the next returned copy to the first person in line (see Container Adapters).
  • Save and load. Write the catalog to a file in the same add Title | Author | Year | Copies format the program already understands, then read it back at startup (see Reading and Writing Text Files).
  • Pagination. Make list print ten books at a time using std::views::chunk(10).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the catalog store books in a std::map<int, Book> with ids it hands out, instead of using vector positions as ids?

    If the id were a vector index, erasing one book would renumber every book after it. A map keyed by a permanent id never shifts, and lookups by id are O(log n).
  2. 2. In sorted_by, why does the title projection declare its return type as const std::string&?

    A lambda's deduced return type drops references, so it would return a copy of the title. Returning const std::string& lets the sort compare the stored titles directly.
  3. 3. The projection std::tie(b->author, b->year) is used to sort books. What order results?

    std::tie builds a tuple of references, and tuples compare lexicographically, the first element first. Ties on author are broken by year.
  4. 4. Why doesn't Book have a separate available counter that borrow and give_back update?

    Redundant state must be kept in sync by every function that changes either part, and one missed update creates a contradiction. Deriving the value removes that risk.
  5. 5. What does std::string_view{"a||b"} | std::views::split('|') produce?

    split produces one piece between every pair of separators, including empty ones. The catalog relies on that to report empty fields instead of silently skipping them.

Summary

  • Give records stable ids and store them in a std::map<int, T>: lookups are O(log n), listings are ordered, and nothing shifts when entries are removed.
  • Use a struct for plain data and a class for the container that enforces rules. Expose read-only access publicly and keep mutable access private.
  • Choose an input format that fits the data (| for fields with spaces), trim generously, validate strictly, and report each error once.
  • Search with views::filter and sort pointers with std::ranges::sort and projections. Return references from projections and use std::tie for multi-key orders.
  • Derive values such as "copies available" instead of storing them twice. One source of truth can't contradict itself.
  • Small helper maps (author counts, loans by member, books per decade) give sorted reports almost for free.

Next: Project: Text Statistics, where you'll analyze a piece of text with std::unordered_map, find the most common and longest words, and count sentences.