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

标签 c++ stl

因此,我使用 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/

相关文章:

C++按值获取数组元素的索引

c++ - 如何从 C++ 中的流执行快速格式化输入?

c++ - 我如何等待子进程结束

c++ - STL List 和 Vector 是如何实现的?

c++ - 如何根据动态属性对项目进行排序?

c++ - 如何使用 C++ 与 asmx 服务通信

c++ - std::string::c_str() 和临时文件

c++ - C++ 中的 vector : Why does the outer dimension give EXC_BAD_ACCESS and the inner dimension doesn't?

c++ - 在 C++ 中向管道发送命令

C++:越来越复杂的错误误导调试器