map/set iterators incompatible - what might be causing it?
I recently started programming in c++ with visual studio 2010, my current projekt (or solution) compiles without errors. Then I start the program and then does the program crach with the following error.
Re: map/set iterators incompatible - what might be causing it?
Originally Posted by cltx
I recently started programming in c++ with visual studio 2010, my current projekt (or solution) compiles without errors.
Compiling without errors has no bearing on whether the program will run successfully.
Then I start the program and then does the program crach with the following error.
And have you debugged your code? You are using Visual C++ which has one of the best debuggers ever developed. When you debug your program using the debugger where does it cause the error?
Secondly, having pointer values as keys is highly dangerous and isn't recommended -- all it will do is eventually lead to bugs that are very hard to find.
Look at your map -- you are using a pointer value (Square*) as a key. So what happens if that pointer is deallocated? You now have to scramble and make sure the map is updated also to remove this, or else you now have an invalid entry in the map. Worse yet, what if that pointer is deleted, and then another call to "new" returns the same pointer value? You now have a map entry that may be referencing old data in the map.
Look at your set<Square*> -- you are using a pointer value as the determining factor, and pointer values can change, become invalid, etc. Again you will be having one heck of a time making sure your set is updated whenever that pointer changes, gets invalidated, etc. If your program gets bigger, at some point you will be fighting a losing battle trying to keep things straight.
The key to a map or objects in a std::set should be something that can't give these issues, types such as int, long, std::string, etc. or a class that has a well-defined operator <. Pointers should not be used as keys to a map or as foundations in any other data structure such as a std::set (even though it is allowable).
Also, it would be much easier for you to typedef your declarations:
Last, I can bet you're overusing pointers. Why do you need to have a Square* to begin with? Why not just deal with Square objects?
If there is no reason to use pointers, then don't use them. The more value-based and the less pointer-based C++ program can be, the less bugs at runtime you will have. Only when it is demonstrably necessary to use pointers and dynamically allocated memory should you do so.
Last edited by Paul McKenzie; July 29th, 2012 at 05:21 AM.