Mega Code Archive
Categories
/
C++
/
Data Structure
Use a map to create a phone directory
#include
#include
#include
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
directory; directory.insert(pair
(name("J"), phoneNum("999-1111"))); directory.insert(pair
(name("C"), phoneNum("999-2222"))); directory.insert(pair
(name("J"), phoneNum("555-3333"))); directory.insert(pair
(name("T"),phoneNum("4444"))); // given a name, find number string str; cout << "Enter name: "; cin >> str; map
::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; }