include iostream include string include map using namespace std class

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream>
#include <string>
#include <map>
using namespace std;
class noSuchBook {
private:
string message;
public:
noSuchBook(string msg){message=msg;};
virtual const string what() {
string m1 = "No such book: ";
return m1.append( message).append("\n");
}
};
class Library {
private:
map<string, string> contents;
public:
bool anyBookForAuthor(string author);
string getAuthorForBook(string bookName);
void addBook(string author, string name);
void delBook(string author);
void print();
};
bool Library::anyBookForAuthor(string author){
return contents.count(author) > 0;
}
string Library::getAuthorForBook(string bookName){
map <string, string>:: const_iterator iter = contents.begin();
while (iter != contents.end()){
if (iter->second == bookName){
return iter->first;
}
iter ++;
}
throw noSuchBook(bookName);
}
void Library::addBook(string author, string name){
contents[author] = name;
}
void Library::delBook(string author){
contents.erase(author);
}
void Library::print(){
map<string,string>::const_iterator iter;
for(iter = contents.begin(); iter != contents.end(); iter++){
cout<<"Book \""<<iter->second<<"\" by "<<iter->first<<endl;
}
}
int main(void){
Library l = Library();
cout << "Initialized library" << endl;
l.print();
l.addBook("A.S. Pushkin", "Poemi, skazki");
l.addBook("L.N. Tolstoy", "Voyna i mir");
l.addBook("T.G. Shevchenko","Kobzar");
cout << "Added books" << endl;
l.print();
string author1 = "L.N. Tolstoy",
author2 = "A.P. Chehov",
book1 = "Kobzar",
book2 = "Povesti";
cout << "Any book for author "<< author1 << ": "<< l.anyBookForAuthor(author1) << endl;
cout << "Any book for author "<< author2 << ": "<< l.anyBookForAuthor(author2) << endl;
try {
cout << "Author for " << book1 << " is ";
cout << l.getAuthorForBook(book1) << endl;
} catch (noSuchBook& e){
cout << e.what();
}
try {
cout << "Author for " << book2 << " is ";
cout << l.getAuthorForBook(book2) << endl;
} catch (noSuchBook& e){
cout << e.what();
}
cout << "Testing erasing:" << endl;
l.print();
l.delBook(author1);
cout << "Deleted " << book1 << endl;
l.print();
return 0;
}