add solution for lab07
This commit is contained in:
42
labs/maps/phonebook2.cpp
Normal file
42
labs/maps/phonebook2.cpp
Normal file
@@ -0,0 +1,42 @@
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <string>
|
||||
using namespace std;
|
||||
|
||||
// Add a number, name pair to the phonebook using a map.
|
||||
void add(map<int, string>& phonebook, int number, const string &name) {
|
||||
map<int, string>::iterator it = phonebook.find(number);
|
||||
if (it != phonebook.end()) {
|
||||
it->second = name;
|
||||
} else {
|
||||
phonebook.insert(pair<int, string>(number, name));
|
||||
}
|
||||
}
|
||||
|
||||
// Given a phone number, determine who is calling.
|
||||
void identify(const map<int, string>& phonebook, int number) {
|
||||
map<int, string>::const_iterator it = phonebook.find(number);
|
||||
if (it == phonebook.end())
|
||||
cout << "unknown caller!" << endl;
|
||||
else
|
||||
cout << it->second << " is calling!" << endl;
|
||||
}
|
||||
|
||||
int main() {
|
||||
// Init
|
||||
map<int, string> phonebook;
|
||||
|
||||
// Add
|
||||
add(phonebook, 1111, "fred");
|
||||
add(phonebook, 2222, "sally");
|
||||
add(phonebook, 3333, "george");
|
||||
add(phonebook, 1234567, "alice");
|
||||
add(phonebook, 7654321, "bob");
|
||||
|
||||
// Test
|
||||
identify(phonebook, 2222);
|
||||
identify(phonebook, 4444);
|
||||
identify(phonebook, 1234567);
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user