How to use multimap to create a phone book in C++

1 Answer

0 votes
#include <iostream>
#include <map>
#include <string>

using std::cout;
using std::endl;
using std::multimap;
using std::string;

class cname {
	string nm;
public:
	cname() {
		nm = "";
	}
	cname(string _nm) {
		nm = _nm;
	}
	const string get() const {
		return nm;
	}
};

bool operator < (cname na, cname nb) {
	return na.get() < nb.get();
}

class cphone {
	string pn;
public:
	cphone() {
		pn = "";
	}
	cphone(string _pn) {
		pn = _pn;
	}
	const string get() const {
		return pn;
	}
};

int main()
{
	multimap<cname, cphone> phone_book;

	phone_book.insert(std::pair<cname, cphone>(cname("Tom"), cphone("709-534-1287")));
	phone_book.insert(std::pair<cname, cphone>(cname("Jerry"), cphone("612-629-9834")));
	phone_book.insert(std::pair<cname, cphone>(cname("Morpheus"), cphone("543-154-9008")));

	multimap<cname, cphone>::iterator it;
	string s = "Jerry";
	it = phone_book.find(s);
	if (it != phone_book.end())
		cout << "Found - Phone number: " << it->second.get() << endl;
	else
		cout << "Name not in phone book" << endl;

	for (it = phone_book.begin(); it != phone_book.end(); it++)
		cout << it->first.get() << " : " << it->second.get() << endl;

	return 0;
}

/*
run:

Found - Phone number: 612-629-9834
Jerry : 612-629-9834
Morpheus : 543-154-9008
Tom : 709-534-1287

*/

 



answered May 7, 2018 by avibootz

Related questions

1 answer 224 views
1 answer 512 views
1 answer 174 views
1 answer 172 views
1 answer 193 views
1 answer 189 views
1 answer 189 views
...