Question

In my SDL program, I am using a map construct to simulate an "infinite" array of objects within a certain class. The code manages to compile fine, but when I run the program, as soon as one of the functions using the maps is trigger, the program crashes, returning a value of 3.

So, here's exactly what I'm doing:

class MyClass
{
     public:
           int MyFunction();
     protected:
           std::map< int, MyObject > MyMap;
}

int MyClass::MyFunction()
{
     ...
     int i;

     if( MyMap.empty() )
     {
          i = 1;
     }
     else
     {
         i = MyMap.size() + 1;
     }

     MyMap[ i ] = PreviouslyDefinedObject;

     return i;

}

When MyFunction() is called from a MyClass object, the crash occurs. It seems to happen whenever anything of use is done with MyMap: it crashes if you comment out the penultimate line and just try to return i, and it crashes if you just set i = 1 and then assign an object to MyMap[i]

This is the first time I've ever used a map, so I'm not certain I'm using them right. Is this a basic mistake somewhere? Can anyone point me in the right direction? Cheers.

Was it helpful?

Solution

Maybe you are calling the function from an uninitialized pointer, like this:

MyClass *obj;
obj->MyFunction();

OTHER TIPS

Maps are used to associate a key with a value. If you're looking for an array, you should use a vector. It will do a better job of simulating an "infinite array" than a map, because a map isn't an array.

Note you can allocate a lot of elements with a vector, usually. If you're really trying to simulate a large array, I'd recommend wrapping up a vector of vectors. With some math, you could create an operator[] for it that indexes into the correct array, to the correct element.

As for your code, there really isn't enough information to determine why it should be crashing, you'd have to try to create a minimal program for us to compile or look at.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top