Files
CSCI-1200/labs/maps/phonebook2.cpp
2025-03-26 13:01:42 -04:00

43 lines
1.1 KiB
C++

#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;
}