C++ STL - 插入自定义类作为映射值 [英] C++ STL - Inserting a custom class as a mapped value

查看:36
本文介绍了C++ STL - 插入自定义类作为映射值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂课:

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;}
};

某些变量(如 canmove 和 notforward)是继承的.接下来,在另一个类中,我创建了一张怪物地图:

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!

推荐答案

简单的方法是

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

另一种方式是

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

还有一个是

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

运算符重载是不必要的,您确实需要重载运算符<用于映射的 key 而不是用于值.我想您可能会感到困惑,因为在第二种情况下需要两次调用 make_pair.

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.

这篇关于C++ STL - 插入自定义类作为映射值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆