gpt4 book ai didi

c++ - 使用 std::map 作为关联数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:04:34 29 4
gpt4 key购买 nike

因此,我使用 std::map 作为关联数组。 map 声明如下:

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

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

CustomClass* pClass = CustomContainer[ID]

Josuttis 说:

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

map 的值属于 CustomClass* 类型。该值会默认为 NULL,还是未定义? (我认为它不会,因为“指针”不是基本数据类型)。我认为它也会在某种程度上依赖于构造函数和那里的行为......想法???

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

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

}

非常感谢!

最佳答案

未初始化的局部指针变量或字段将具有未定义的值,就像未初始化的 int(或者,一般来说,POD 类型)局部变量或字段一样。但是,这与手头的问题无关。

当您在 map 上使用 operator[] 并创建一个新条目时,它是默认初始化的。这意味着指针的空指针值(int 为 0,等等)。它永远不会是未定义的。

如果您确实需要检查 map 中是否存在具有此类键的项目,并且不想要新条目,请使用 find() 成员函数,并将返回的迭代器与结束()

关于c++ - 使用 std::map 作为关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1540182/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com