I recently made a dynamic quadtree for moving objects for a game I'm creating. Initially i used the std::vector to contain all objects present in the current rectangle and after some optimization and fixing stack overflow it's now working perfectly with 1000+ moving objects.
However, a friend of mine told me ( or rather a chat ) that I should be using std::set rather than std::vector because it uses less alloc/moving/resizing-calls and has improved access time.
My naive approach was simply just change all std::vector operations to be std::set, change a few loops to use iterators instead of an integer and so forth. The code in it self is exactly "the same" as the one with vectors but for some reason it's crashing inside the "Quadtree::update()" method which simply updates the quadtree which contains moving objects.
The function looks like this:
void Quadtree::update() {
if ( status == QuadStatus::BRANCH && hasLeafChildren() )
merge();
if(status == QuadStatus::LEAF) {
for( auto it = objects.begin(); it != objects.end(); ++it) {
if(!inBounds((*it)->getX(), (*it)->getY()) ) {
GameObject* o = (*it);
it = objects.erase(it); // THIS IS WHAT IS CAUSING THE CRASH!!!
parent->addObject(o);
}
}
return;
}
else
for(int i = 0; i < 4; i++) {
if(nodes[i] != nullptr)
nodes[i]->update();
}
}
Apparently it's the line "it = objects.erase(it)" that is making the program crash - here is the call stack:
0 0x00449a26 std::_Rb_tree_increment(std::_Rb_tree_node_base const*)
1 0x004ceed6 std::_Rb_tree_const_iterator<GameObject*>::operator++ c:\\mingw-4.7.1\\lib\\gcc\\mingw32\\4.7.1\\include\\c++\\bits\\stl_tree.h 2692 0x00403cca Quadtree::update C:\\Users\\Victor\\Documents\\CodeLite\\OneGameAMonth\\TinyQuest\\Quadtree.cpp 2133 0x00403d58 Quadtree::update C:\\Users\\Victor\\Documents\\CodeLite\\OneGameAMonth\\TinyQuest\\Quadtree.cpp 2314 0x00403d58 Quadtree::update C:\\Users\\Victor\\Documents\\CodeLite\\OneGameAMonth\\TinyQuest\\Quadtree.cpp 2315 0x00401ad1 main C:\\Users\\Victor\\Documents\\CodeLite\\OneGameAMonth\\TinyQuest\\main.cpp 79
I'm not entirely sure why ( I think it's an overflow ) but isn't std::set suppose to use LESS operations than an vector?
Kind regards, Moonkis