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 223 views
2 answers 239 views
1 answer 114 views
1 answer 66 views
3 answers 327 views
...