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 key 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 User {
	string uid;
	string uname;
public:
	User(string _name, string _id)
		:uid(_id), uname(_name)
	{}
	const string& get_id() const {
		return uid;
	}
	const string& get_name() const {
		return uname;
	}
	bool operator < (const User& uObj) const
	{
		if (uObj.uid < this->uid)
			return true;
	}
};

int main()
{
	map<User, int> mUser;

	mUser.insert(std::make_pair<User, int>(User("Tom", "123498"), 12001));
	mUser.insert(std::make_pair<User, int>(User("Jerry", "983723"), 11073));
	mUser.insert(std::make_pair<User, int>(User("Morpheus", "376511"), 10987));

	map<User, int>::iterator it = mUser.begin();
	for (; it != mUser.end(); it++)
	{
		cout << it->first.get_name() << " : " << it->first.get_id() 
			 << " - "  << it->second << std::endl;
	}

	return 0;
}

/*
run:

Jerry : 983723 - 11073
Morpheus : 376511 - 10987
Tom : 123498 - 12001

*/

 



answered May 5, 2018 by avibootz

Related questions

1 answer 212 views
2 answers 218 views
1 answer 97 views
1 answer 50 views
3 answers 301 views
...