Problem statement:
You have to perform operations on a map where each key is a student's name and the value is their corresponding phone number. You are given Q queries, each representing a type of operation to be performed. The possible query types are:
add - Add the phone number y of student x to the map.
erase - Erase the phone number of student x from the map.
find - Print the phone number of student x. If the student is not found, print "Not found".
Sample Input:
The first line of input contains an integer Q, representing the number of queries. This is followed by Q lines, each containing a query.
3
add sam 99912222
add tom 11122222
find sam
find edward
Sample Output:
For each "find" query, print the phone number of the student or "Not found" if the student is not present.
99912222
Not found
Explanation:
In this example, we have three queries:
The first query is an "add" query, adding the phone number 99912222 for student "sam" to the map.
The second query is another "add" query, adding the phone number 11122222 for student "tom" to the map.
The third query is a "find" query, searching for the phone number of student "sam". Since "sam" is present in the map, the corresponding phone number 99912222 is printed.
The fourth query is another "find" query, searching for the phone number of student "edward". Since "edward" is not present in the map, "Not found" is printed.
#include <iostream>
#include <map>
using namespace std;
int main() {
int Q;
cin >> Q;
map phoneBook;
while (Q--) {
string query;
cin >> query;
if (query == "add") {
string name;
int phoneNumber;
cin >> name >> phoneNumber;
phoneBook[name] = phoneNumber;
} else if (query == "erase") {
string name;
cin >> name;
phoneBook.erase(name);
} else if (query == "find") {
string name;
cin >> name;
if (phoneBook.find(name) != phoneBook.end()) {
cout << phoneBook[name] << endl;
} else {
cout << "Not found" << endl;
}
}
}
return 0;
}
Code Explanation
We start by including the necessary header files, including