add solution for lab07

This commit is contained in:
2025-03-26 12:59:54 -04:00
parent eaa3021d47
commit 48d8b8fcfd
7 changed files with 148 additions and 0 deletions

42
labs/maps/phonebook2.cpp Normal file
View 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;
}