[英]Unordered Map with a custom class
我在这里是新问题,这是我的第一个问题。(我在查看此站点时发现了我问题的一些答案,但由于我的情况与我有所不同,所以我不明白它们的含义。)首先让我向您展示一些代码:这是我的课:
class citems{
public:
char* name;
int colorR;
int colorG;
int colorB;
int type;
citems(char* name, int colorR, int colorG, int colorB, int type)
{
this->name = name;
this->colorR = colorR;
this->colorG = colorG;
this->colorB = colorB;
this->type = type;
}
};
然后,我将创建一个函数来执行此操作,但是列表很长:
citems getObjectFromId(int ID)
{
static unordered_map <int, citems> item;
static bool init = false;
if (!init)
{
item[123546]= citems("Name", 181,179, 0, 9);
init = true;
}
return item[ID];
}
因此,我可以致电商品ID,并随时获取单独的颜色,类型和名称。 到目前为止一切正常,但是当我编译时出现此错误:
c:\\ program files(x86)\\ Microsoft Visual Studio 11.0 \\ vc \\ include \\ unordered_map(239):错误C2228:'.first'的左边必须有class / struct / union
所以我读到我必须做我自己的EqualOperator或类似的东西,但是我似乎无法从中得到逻辑。 提前致谢。
对于T& operator[]( const Key& key )
映射类型必须满足DefaultConstructible要求。 这意味着您的类citems需要一个默认的构造函数:
class citems{
public:
//...
/* possible form 1 */
citems() {
}
/* possible form 2 ( default parameter values)*/
citems( char* name = 0, int colorR = -1, int colorG = -1,
int colorB = -1, int type = -1) {
}
};
还要注意, T& operator[]( const Key& key )
返回对该值的引用,该值映射到等效于key的键,如果该键尚不存在,则执行插入操作。 如果您不想在地图中没有给定键的情况下插入新元素,而是要更改现有元素,则必须首先使用find()
或使用insert()
来检查地图上是否存在此类元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.