C++ STL - Inserting a custom class as a mapped val

2019-09-16 04:29发布

I have a class:

class Monster : public Player
{
public:
    // Copy constructor - used for populating monster list in Game class
    Monster(int newType)
    {
        type = newType;
        canmove = true;
        notforward = false;
    }

    int type;

    bool operator==(const Monster& m) const {return type == m.type;}
    bool operator!=(const Monster& m) const {return type != m.type;}
    bool operator< (const Monster& m) const {return type <  m.type;}
    bool operator<=(const Monster& m) const {return type <= m.type;}
    bool operator> (const Monster& m) const {return type >  m.type;}
    bool operator>=(const Monster& m) const {return type >= m.type;}
};

Some variables (like canmove and notforward) are inherited. Next, in a different class, I create a map of monsters:

map<pair<int, int>, Monster> monsters; // Pair used for x and y coordinate

monsters.insert(make_pair(10, 10), Monster(10)); 
// Error - No instance of overloaded function

How can I get the Monster instances into the monsters map? I added all the operator overloads just so I could insert, but it doesn't work!

标签: c++ stl
1条回答
We Are One
2楼-- · 2019-09-16 05:23

Simple way is

monsters[make_pair(10, 10)] = Monster(10);

another way is

monsters.insert(make_pair(make_pair(10, 10), Monster(10)));

yet another is

monsters.insert(map<pair<int, int>, Monster>::value_type(make_pair(10, 10), Monster(10)));

Operator overloads are unnecessary, you do need to overload operator< for the key of a map but not for the value. I think maybe you got confused because two calls to make_pair are necessary in the second case.

查看更多
登录 后发表回答