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

强颜欢笑 提交于 2019-12-25 04:10:24

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/16475141/c-stl-inserting-a-custom-class-as-a-mapped-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!