Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,855 questions

51,776 answers

573 users

How to use user defined class objects as phone book in map with C++

1 Answer

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

using std::cout;
using std::endl;
using std::map;
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()
{
	map<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")));

	map<cname, cphone>::iterator it;

	it = phone_book.find(cname("Jerry"));
	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 5, 2018 by avibootz

Related questions

1 answer 162 views
1 answer 304 views
1 answer 486 views
2 answers 218 views
1 answer 160 views
1 answer 97 views
...