Library Manager
Completed
Model Book and Library classes. Commands: add ID TITLE, borrow ID USER, return ID, user USER (list the titles a user has, sorted, or none), status (all books by id: ID TITLE available|USER). Print error for impossible actions.
Input
n, then n commands (single-word titles).
Output
Errors and listings.
Example
Input
9 add B2 Dune add B1 Emma borrow B1 ann borrow B2 ann borrow B1 bob user ann return B1 return B1 status
Output
error Dune Emma error B1 Emma available B2 Dune ann
Editor
C++
Hints
map::insert returns whether the key was new.
An empty borrower string means available.
Solution explanation
Classes, maps, sets and status returns together make a small but complete system.
Show solution
#include <iostream>
#include <map>
#include <set>
#include <string>
using namespace std;
struct Book {
string title;
string borrower;
};
class Library {
public:
bool add(const string &id, const string &title) {
return books_.insert({id, Book{title, ""}}).second;
}
bool borrow(const string &id, const string &user) {
auto it = books_.find(id);
if (it == books_.end() || !it->second.borrower.empty()) return false;
it->second.borrower = user;
return true;
}
bool giveBack(const string &id) {
auto it = books_.find(id);
if (it == books_.end() || it->second.borrower.empty()) return false;
it->second.borrower.clear();
return true;
}
set<string> titlesOf(const string &user) const {
set<string> titles;
for (const auto &[id, b] : books_)
if (b.borrower == user) titles.insert(b.title);
return titles;
}
void status() const {
for (const auto &[id, b] : books_)
cout << id << " " << b.title << " " << (b.borrower.empty() ? "available" : b.borrower) << "\n";
}
private:
map<string, Book> books_;
};
int main() {
Library lib;
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string cmd, a, b;
cin >> cmd;
bool ok = true;
if (cmd == "add") {
cin >> a >> b;
ok = lib.add(a, b);
} else if (cmd == "borrow") {
cin >> a >> b;
ok = lib.borrow(a, b);
} else if (cmd == "return") {
cin >> a;
ok = lib.giveBack(a);
} else if (cmd == "user") {
cin >> a;
auto titles = lib.titlesOf(a);
if (titles.empty()) cout << "none";
bool first = true;
for (const auto &t : titles) {
cout << (first ? "" : " ") << t;
first = false;
}
cout << "\n";
} else {
lib.status();
}
if (!ok) cout << "error\n";
}
return 0;
}