Using std :: map as an associative array

So, I use std :: map as an associative array. The card is declared as such:

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

Subsequently, I use the CustomContainer object as an associative array, for example,

CustomClass* pClass = CustomContainer[ID]

Josuttis states:

If you use the key as an index for which an element does not yet exist, a new element is automatically added to the map. The value of the new element is initialized by the default constructor of its type. Thus, to use this function, you cannot use a value type that does not have a default constructor

The map value is of type CustomClass *. Will the default be NULL, or is it undefined? (I think this is not the case, since the "pointer" is not a fundamental data type). I would have thought that he would also rely on the constructor and the behavior there .... thoughts ???

The only CustomClass constructor is as follows:

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

}

Thanks a lot!

+1
source share
4 answers

An uninitialized local pointer variable or field will have the value undefined, as well as an uninitialized local variable or field of type t20> (or, as a rule, POD). However, this has nothing to do with the issue.

operator[] , , . ( 0 int s ..). undefined.

, , , find() member end().

+13

map:: find .

std::map<int, CustomClass*>::iterator i = CustomContainer.find(ID);
if (i != CustomContainer.end())
{
    CustomClass* pClass = i->second;
    ...
+9

Your map stores CustomClass *, so calling CustomContainer [newID] creates a pointer, not an instance of CustomClass. The pointer value will be undefined - even if you are lucky and it is NULL first, you should not count on this behavior.

Yes, I am wrong in this last part.

You can check the identifier on the card as follows:

(CustomContainer.find(someID) == map<int,CustomClass>::end)
0
source

All Articles