Show contents
Chapter 6 of 7 · 25 min
Project: a lending library
By the end of this chapter, you'll be able to
- Design a class from the rules of a real problem
- Combine std::vector, std::map and the standard algorithms in a class
- Read and interpret commands typed on the keyboard
- Test a program with a scenario whose result you know
- Add a business rule without breaking the existing code
Step 1: the rules and the design
The library's rules:
- you can't add the same title twice;
- you can only borrow a book that exists and is available;
- you can only return a book that was borrowed;
- at any time, you can display the status of each book.
A class Library will guarantee these rules. Inside, two containers, both private:
std::vector<std::string> titles_: the books, in the order they were added;std::map<std::string, std::string> loans_: for each borrowed title, the borrower's name. A book that isn't in the map is available.
The main program reads commands from the keyboard (add, borrow, return, status) and calls the matching methods.
The method returns the message, which main displays.
Text description of the animation
- The user types a command and its arguments.
- main reads the first word, recognises the command, then reads the title and the member.
- The method checks that the book exists and isn't already lent out. Here, it is: refused.
- Once the book has been returned, both conditions are met.
- The loan is recorded in the private map. Nobody else can change it.
- The method returns the message, which main displays.
Step 2: the program
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <vector>
class Library {
public:
bool add(const std::string& title) {
if (owns(title)) {
return false;
}
titles_.push_back(title);
return true;
}
std::string borrow(const std::string& title, const std::string& member) {
if (!owns(title)) {
return "Unknown book: " + title;
}
if (loans_.contains(title)) {
return title + " is already borrowed by " + loans_.at(title);
}
loans_[title] = member;
return member + " borrows " + title;
}
std::string give_back(const std::string& title) {
auto it = loans_.find(title);
if (it == loans_.end()) {
return title + " wasn't borrowed";
}
std::string member = it->second;
loans_.erase(it);
return member + " returns " + title;
}
void show_status() const {
for (const std::string& title : titles_) {
auto it = loans_.find(title);
std::cout << "- " << title << ": "
<< (it == loans_.end() ? "available" : "with " + it->second) << "\n";
}
}
private:
bool owns(const std::string& title) const {
return std::find(titles_.begin(), titles_.end(), title) != titles_.end();
}
std::vector<std::string> titles_;
std::map<std::string, std::string> loans_; // title -> borrower
};
int main() {
Library library;
std::string command;
while (std::cin >> command) {
if (command == "add") {
std::string title;
std::cin >> title;
std::cout << (library.add(title) ? "Added: " : "Already there: ") << title << "\n";
} else if (command == "borrow") {
std::string title, member;
std::cin >> title >> member;
std::cout << library.borrow(title, member) << "\n";
} else if (command == "return") {
std::string title;
std::cin >> title;
std::cout << library.give_back(title) << "\n";
} else if (command == "status") {
library.show_status();
} else {
std::cout << "Unknown command: " << command << "\n";
}
}
return 0;
}
A few choices worth noticing:
- the methods return a message instead of displaying it themselves: the class doesn't depend on the console, and it could be reused in a web or mobile app;
ownsis private: it's an internal tool, not an action offered to the user;show_statusisconst: displaying changes nothing;it->secondrefers to the value of a pair in the map (andit->firstto the key);loans_.erase(it)removes a pair from the map;- the method is called
give_backbecausereturnis a C++ keyword, which can't be used as a name.
Step 3: test a complete scenario
We write a scenario that goes through every rule, and predict the output before running the program:
add Algorithms
add Networks
add Cooking
add Networks
borrow Networks Kofi
borrow Networks Mei
return Networks
borrow Networks Mei
borrow Astronomy Mei
status
Added: Algorithms
Added: Networks
Added: Cooking
Already there: Networks
Kofi borrows Networks
Networks is already borrowed by Kofi
Kofi returns Networks
Mei borrows Networks
Unknown book: Astronomy
- Algorithms: available
- Networks: with Mei
- Cooking: available
Titles are read with >>: so they can't contain spaces. For a more comfortable version, you'd read the rest of the line with std::getline.
Your turn
Worked exercise
Worked exercise: limiting loans
Add a rule: a member can't have more than 2 books borrowed at the same time. Write a private method int loan_count(const std::string& member) const, use it in borrow, and return the message Mei already has 2 books borrowed when refusing. To test without the keyboard, the solution calls the methods directly.
Hint 1
std::count_if goes through the map. Each item is a pair: loan.second is the borrower's name.Hint 2
member in the lambda, you have to capture it: [&member](const auto& loan) { return loan.second == member; }. The & means the lambda accesses it by reference.Show the solution and common mistakes
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <vector>
class Library {
public:
void add(const std::string& title) {
if (!owns(title)) {
titles_.push_back(title);
}
}
std::string borrow(const std::string& title, const std::string& member) {
if (!owns(title)) {
return "Unknown book: " + title;
}
if (loans_.contains(title)) {
return title + " is already borrowed by " + loans_.at(title);
}
if (loan_count(member) >= MAX_LOANS) {
return member + " already has " + std::to_string(MAX_LOANS) + " books borrowed";
}
loans_[title] = member;
return member + " borrows " + title;
}
private:
static constexpr int MAX_LOANS = 2;
bool owns(const std::string& title) const {
return std::find(titles_.begin(), titles_.end(), title) != titles_.end();
}
int loan_count(const std::string& member) const {
return static_cast<int>(std::count_if(loans_.begin(), loans_.end(),
[&member](const auto& loan) { return loan.second == member; }));
}
std::vector<std::string> titles_;
std::map<std::string, std::string> loans_;
};
int main() {
Library library;
library.add("Algorithms");
library.add("Networks");
library.add("Cooking");
std::cout << library.borrow("Algorithms", "Mei") << "\n";
std::cout << library.borrow("Networks", "Mei") << "\n";
std::cout << library.borrow("Cooking", "Mei") << "\n";
std::cout << library.borrow("Cooking", "Kofi") << "\n";
return 0;
}
Mei borrows Algorithms
Mei borrows Networks
Mei already has 2 books borrowed
Kofi borrows Cooking
static constexpr int MAX_LOANS = 2; declares a constant belonging to the class, known at compile time. To switch to 3 books, only one line changes. std::to_string turns a number into text.
Common mistakes:
- Checking the limit before checking that the book exists: a member at the limit would get "2 books borrowed" for a title that doesn't exist, which is misleading.
- Writing
[](const auto& loan) { return loan.second == member; }without a capture: the compiler refuses, because the lambda doesn't knowmember.
Summary
- 1Start from the rules of the problem to design the class and its public methods.
- 2The internal containers (vector, map) stay private: only the class applies the rules.
- 3The methods return results; main handles the dialogue with the user.
- 4Test with a scenario that goes through every rule, and predict the output before running.
- 5A new rule is added inside the class, without touching the code that uses it.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.