使用std :: map作为关联数组 [英] Using a std::map as an associative array

查看:139
本文介绍了使用std :: map作为关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我使用std :: map作为关联数组。映射如下声明:

So, I'm using a std::map as an associative array. The map is declared as such:

std::map<int, CustomClass*> CustomContainer;

稍后,我使用CustomContainer对象作为关联数组,例如

Later on, I use the CustomContainer object as an associative array, e.g.,

CustomClass* pClass = CustomContainer[ID]

Josuttis说:

Josuttis states:


如果使用键作为索引,但没有元素存在,自动插入地图。新元素的值由其类型的默认构造函数初始化。因此,要使用此功能,您不能使用没有默认构造函数的值类型

If you use a key as the index, for which no element yet exists, a new element get inserted into the map automatically. The value of the new element is initialized by the default constructor of its type. Thus, to use this feature you can't use a value type that has no default constructor

地图的值为类型CustomClass *。将值默认为NULL,还是未定义? (我认为它不会,因为指针不是一个基本的数据类型)。我认为它也将有点依赖于构造函数和那里的行为....思想?

The value of the map is of type CustomClass*. Will the value default to NULL, or is it undefined? (I think that it wouldn't, as "pointer" isn't a fundamental data type). I would think it would also rely somewhat on the constructor and the behavior there as well.... thoughts???

CustomClass的唯一构造函数如下所示:

The only constructor of CustomClass looks like this:

CustomClass::CustomClass(ClassA param1, ClassB param2, ClassC param3, ClassD param4)
:privateClassA(param1),
privateClassB(param2),
privateClassC(param3),
privateClassD(param4)
{

}

推荐答案

未初始化的本地指针变量或字段将具有未定义的值,就像未初始化的 int (或者,一般来说,POD类型)局部变量或字段。

An uninitialized local pointer variable or field will have undefined value, just like uninitialized int (or, in general, POD-type) local variable or field would. However, this has nothing to do with question at hand.

当您在地图上使用 operator [] 时,它创建一个新条目,它是默认初始化。这意味着指针的空指针值(对于 int s为0,以此类推)。它永远不会被定义。

When you use operator[] on map, and it creates a new entry, it is default-initialized. This means null pointer value for pointers (and 0 for ints, and so on). It would never be undefined.

如果你实际上需要检查在地图中是否有这样的键的项目,并且不想要新的条目,使用 find()成员函数,并将返回的迭代器与 end()比较。

If you actually need to check if there is an item with such key in the map or not, and do not want new entries, use find() member function, and compare the returned iterator to end().

这篇关于使用std :: map作为关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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