   Vector resizing problems (C++)
  So I'm trying to make a system to manage my game objects in a 2D game, so I've got a vector that holds all of the objects and is used to perform updating an rendering on them.  The problem I'm having is adding elements to the vector.  I'm trying to insert them by the correct Z order to make the rendering work right, but I think the problem is I'm confused as to when the capacity is actually updated.  Here's my source:void ObjectManager::AddObject(GameObject* obj){if (obj!=NULL){if (managedObjects.size()>0){vector<GameObject*>::iterator myIter;for (myIter=managedObjects.begin();myIter!=managedObjects.end(); myIter++){if (obj->GetZOrder()< (*myIter)->GetZOrder()){managedObjects.insert(myIter,obj);m_iManagedSprites++;return;}}}managedObjects.push_back(obj);m_iManagedSprites++;}}So initially I reserved 100 capacity in the vector, so it works up to 100 objects, but when you try and add more it crashes the program.  Documentation that I've been reading says that insert and push_back automatically resize the capacity of the vector if there isn't enough room, so I thought that after I hit 100 objects, it would resize the vector and let me continue to insert elements.  So am I doing something wrong here?   
  Without looking too closely at your code; if you have a vector of classes, you need to make sure that your class correctly implements a default constructor, destructor, a copy constructor, and operator=. If it doesn't, you can't use it in a STL container - Although you can use a pointer (or smart pointer) to it.EDIT: Looking at the code again, you're already using pointers to objects in the vector. Are you sure they'r ebeing correctly allocated?EDIT #2: What do you mean it "crashes your program"? What line does it crash on? Where does the debugger show the problem is? In what way does it crash? Does it give you an access violation? Does the app just exit? Does it set the building on fire?   ;  That is odd, it should resize the vector once the capacity is not big enough to hold the required number of objects. Have you tried debugging to see where the exact source of the crash is ?Another thing to watch out for is this.. From STL docs:[5] A vector's iterators are invalidated when its memory is reallocated. Additionally, inserting or deleting an element in the middle of a vector invalidates all iterators that point to elements following the insertion or deletion point. It follows that you can prevent a vector's iterators from being invalidated if you use reserve() to preallocate as much memory as the vector will ever use, and if all insertions and deletions are at the vector's end.If you are holding any iterators into the vector somewhere else in the code then it will be invalidated. I don't know if you are, but it's something to be careful of in any case..   ;  It crashes just as soon as it tries to add the 101th element.  It gives me the error:---------------------------Microsoft Visual C++ Debug Library---------------------------Debug Assertion Failed!Program: ...y Documents\Visual Studio 2008\Projects\Crims\Debug\Crims.exeFile: c:\program files\microsoft visual studio 9.0\vc\include\vectorLine: 116Expression: ("this->_Has_container()", 0)For information on how your program can cause an assertionfailure, see the Visual C++ documentation on asserts.(Press Retry to debug the application)---------------------------Abort   Retry   Ignore   ---------------------------Edit:  My problem probably is the iterator breaking in another method, I'll work on that.Edit2:  Actually, my whole system of sprite management seems flawed.  Is there an article that shows some techniques about how to do this, I checked but couldn't easily find one.  Right now I've got a method that updates all the sprites, and if the update for a sprite returns a sprite, then it adds it to the list in another function which can break the iterator in the update function, plus is stupid because it allows ambiguity in this situation:Sprite in update adds spriteFunction to add the sprite to the list may insert it before or after where the iterator is in the update function (depending on z order)Therefore it's unknown whether or not the newly added sprite has update called on it this frame, or the next one.Another option I could do would be to queue up sprites to add, and then add them all at the end of the update function.  Would this be better?   ;  Add a break point when the size is 100 and step into the code.or hit retry and look at the call stack.mandatory link;  Ok so I fixed it but I'm worried that my manager structure is poor.  Let me know how this sounds:I have an ObjectManager class that has functions RenderObjects(), UpdateObjects(), AddObject, A constructor that allocated 100 elements to a vector, and a destructor that iterates through the vector and calls delete on every element then clears the vector.The UpdateObjects() function iterates through all the elements and calls their Update() method, which returns an OBJECTACTION (custom data type, either DIE,ADDOBJECT, or DEFAULT).  If it returns ADDOBJECT then I call the objects AddObject function, which returns an object pointer.  This newly returned object is now added to a queue.  After update has been called on all the currently existing objects, I now go through the queue and use queue.front() to send the Object to the AddObject() function of the sprite manager, then I pop the element from the queue, and continue this until the queues size is 0.  This means that all newly added objects don't get Update() called on them until the next frame (but they do get rendered), which seems correct.Does this sound like an OK outline for a sprite management system, or am I doing it poorly?   ;  "I have an ObjectManager class that has functions RenderObjects(), UpdateObjects(), AddObject, A constructor that allocated 100 elements to a vector, and a destructor that iterates through the vector and calls delete on every element then clears the vector."Now, I'm no expert but in C++, if you have a vector of Custom objects/Class, whenever the vector is release from memory, the vector will automatically call the Destructor of you class - this means that you do NOT need to call delete on every element in your vector if the destructor is implemented correctly.   ;Quote:Original post by gp343"I have an ObjectManager class that has functions RenderObjects(), UpdateObjects(), AddObject, A constructor that allocated 100 elements to a vector, and a destructor that iterates through the vector and calls delete on every element then clears the vector."Now, I'm no expert but in C++, if you have a vector of Custom objects/Class, whenever the vector is release from memory, the vector will automatically call the Destructor of you class - this means that you do NOT need to call delete on every element in your vector if the destructor is implemented correctly.Err, I don't think that's the case, either that or I'm just not understanding what you mean.  My vector contains pointers, so when I test it if you just empty the vector it doesn't seem to be deleting the actual pointer references (memory doesn't look like it gets reclaimed if I take that out).  When the vector is released from memory doesn't it just get rid of the vector itself (which is just a series of pointers to elements really, right).  If it DID call delete then it would cause problems with things, like say I had an explicit global reference to only one of the pointers in the vector, after I get rid of the vector I should still have that reference even though the object was under the management of the manager class (which has the vector).  Meaning after I stop the management I couldn't access the global pointer to that specific element (which in reality I don't actually need once the vector is gone, but I should be able to if I wanted to).   ;  Some notes:1) It's supposed to be the caller's responsibility to make sure that what is passed in is valid. Usually, in C++, we avoid checks for NULL input pointers by just using references instead; there's no such thing as a "null reference" unless the calling code already invoked undefined behaviour. I can see that it makes sense to use the pointer here since you're manipulating a vector of pointers, but we probably ought to treat a NULL pointer here more seriously. There's probably something wrong with the calling code if it passes a NULL, so we should make the code break here and figure out what's up.2) You don't really need to handle the "empty vector" case separately, and you don't need to loop to search, either. What you're trying to do is find the position for insertion, in a sorted vector, and then insert there. As it happens, there's a standard library algorithm for that, and it works just fine with an empty vector, anyway (it will just return the .begin() of the vector, which equals the .end() of the vector in that case, and is of course an appropriate place to .insert() the element.) All we need to do is define the comparison of elements, in a separate function. (This is probably a good idea anyway; it will likely be useful elsewhere, too.)3) There is absolutely no reason to count up the "m_iManagedSprites" separately. The vector already knows its .size() (and in fact, you've already been using this fact).4) Once we make the resulting possible simplifications, the function body become s short enough that we ought to just undo that guard clause thingy after all. ;)bool compareByZOrder(GameObject* a, GameObject* b){return a->GetZOrder() < b->GetZOrder();}void ObjectManager::AddObject(GameObject* obj){assert(obj);managedObjects.insert(std::lower_bound(managedObjects.begin(), managedObjects.end(), compareByZOrder), obj);}Yes, It's Really That Simple(TM).5) You might want to think about those names a little more. "GameObject" isn't really much more descriptive than "Object"; and anyway, trying to make everything in your game derive from a top-level, generic "object" is probably a trap. And a name like "ObjectManager" is similarly undescriptive. What does it mean to "manage" objects?Quote:Err, I don't think that's the case, either that or I'm just not understanding what you mean. My vector contains pointers, so when I test it if you just empty the vector it doesn't seem to be deleting the actual pointer references (memory doesn't look like it gets reclaimed if I take that out). When the vector is released from memory doesn't it just get rid of the vector itself (which is just a series of pointers to elements really, right). If it DID call delete then it would cause problems with things, like say I had an explicit global reference to only one of the pointers in the vector, after I get rid of the vector I should still have that reference even though the object was under the management of the manager class (which has the vector). Meaning after I stop the management I couldn't access the global pointer to that specific element (which in reality I don't actually need once the vector is gone, but I should be able to if I wanted to).The vector cleans up its allocations; you clean up your allocations. So do delete the things that you allocated with new, but there is no need to .clear() the vector afterwards.But be careful. If you're just going through and calling 'delete' on every pointer in the vector at the end, you have to know that nothing else is holding pointers to the same allocations, and also that the pointers within the vector are unique. In other words, you need "ownership semantics".   ;  I didn't read the entire post and replies..."managedObjects.push_back(obj);" (after the end of if block)the above statement is being called, irrespective of the size of managedObjects and irrespective of the z values.  Was it intensional????This may lead to deleting the same block more than once..   