How do I overload the < operator to be able to use class objects with Map container?
Feb 5, 2021 at 5:27pm UTC
I'm following the Learncpp site and it has stuff on operator overloading but I cant seem to figure it out for using a class object, I've been trying to figure this out for hours and all the stuff i found on google hasnt really brought me any luck. I created this small program to isolate my incident so its easier to solve.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
#include <iostream>#include <map>
#include <string>
#include <iterator>
using std::string;
using std::cout;
using std::endl;
using std::map;
using std::pair;
class Character;
class Item
{
public :
Item(const string& name): m_name(name)
{}
string GetItemName() const { return m_name; }
friend bool operator < (const Item& a, const Character& b)
{
using pair = std::pair< const string, int >;
return pair{ a.GetItemName(), a.GetItemName() } < pair { b.GetItemInventoryAmount(), b.GetItemInventoryAmount() };
}
private :
string m_name{ "Item" };
};
class Character
{
public :
Character(const string& name): m_name(name)
{}
void AddItemToInventory(Item& item, int amountToAdd);
void OpenInventory();
int GetItemInventoryAmount() const { return m_itemInventoryStock; }
private :
string m_name{ "Character" };
map<Item, int > m_inventory{};
int m_itemInventoryStock{ 0 };
};
void Character::AddItemToInventory(Item& item, int amountToAdd)
{
m_inventory.insert(std::make_pair(item, amountToAdd));
}
void Character::OpenInventory()
{
map<Item, int >::iterator it = m_inventory.begin();
}
int main()
{
Character Link("Link" );
Item Rupee("Rupee" );
}
Feb 5, 2021 at 5:36pm UTC
If you have a map where Item is the key, you need to be able to tell the compiler how to order two Items.
So you need an operator like
1 2 3 4
friend bool operator <(const Item& a, const Item& b)
{
return a.GetItemName() < b.GetItemName();
}
Last edited on Feb 5, 2021 at 5:38pm UTC
Feb 5, 2021 at 5:39pm UTC
What is the operator< supposed to do?
Feb 5, 2021 at 5:50pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include <iostream>
using namespace std;
class MyClass {
public :
int a, b;
bool operator < (MyClass& two) {
return a < two.b;
}
};
int main()
{
MyClass one;
MyClass two;
one.a = 5;
two.b = 10;
cout << (one < two);
}
Last edited on Feb 5, 2021 at 5:50pm UTC
Feb 5, 2021 at 5:58pm UTC
Thanks guys!
Topic archived. No new replies allowed.