Use a map to create a phone directory: string class
#include <iostream>
#include <map>
#include <string>
using namespace std;
class name {
string str;
public:
name() {
str = "";
}
name(string s) {
str = s;
}
string get() {
return str;
}
};
// Define less than relative to name objects.
bool operator<(name a, name b){
return a.get() < b.get();
}
class phoneNum {
string str;
public:
phoneNum() {
str = "";
}
phoneNum(string s) {
str = s;
}
string get() {
return str;
}
};
int main()
{
map<name, phoneNum> directory;
directory.insert(pair<name, phoneNum>(name("J"), phoneNum("999-1111")));
directory.insert(pair<name, phoneNum>(name("C"), phoneNum("999-2222")));
directory.insert(pair<name, phoneNum>(name("J"), phoneNum("555-3333")));
directory.insert(pair<name, phoneNum>(name("T"),phoneNum("4444")));
// given a name, find number
string str;
cout << "Enter name: ";
cin >> str;
map<name, phoneNum>::iterator p;
p = directory.find(name(str));
if(p != directory.end())
cout << "Phone number: " << p->second.get();
else
cout << "Name not in directory.\n";
return 0;
}
Related examples in the same category