查询四叉树导致溢出

时间:2012-12-10 22:01:42

标签: c++ recursion quadtree

我希望能够检查四叉树中包含在与区域相交的节点中的所有元素。但问题是,如果我在一个只有高度为2的小部分上调用Query,则会发生堆栈溢出。

执行以下操作的方法有哪些(或更少错误)?

//Call
query_area = new a2de::Rectangle(_mouse->GetX(), _mouse->GetY(), 100.0, 100.0, a2de::YELLOW, false);
_selected_elements = _qt->Query(*query_area);

//...
//Definitions
template<typename T>
std::vector<T> QuadTree<T>::Query(a2de::Rectangle& area) {
    return QueryNode(this, area);
}

template<typename T>
std::vector<T> QuadTree<T>::QueryNode(QuadTree<T>* node, a2de::Rectangle& area) {
    std::vector<T> contained_elements;
    if(node->_bounds.Intersects(area)) {
        if(IsLeaf(node) == false) {
            std::vector<T> child_results;
            for(std::size_t i = 0; i < 4; ++i) {
                child_results = QueryNode(_children[i], area);
                for(std::vector<T>::iterator _iter = child_results.begin(); _iter != child_results.end(); ++_iter) {
                    contained_elements.push_back(*_iter);
                }
                child_results.clear();
            }
        } else {
            for(std::vector<T>::iterator _iter = _elements.begin(); _iter != _elements.end(); ++_iter) {
                contained_elements.push_back(*_iter);
            }
        }
    }
    return contained_elements;
}

1 个答案:

答案 0 :(得分:0)

固定。它与使用this指针调用QueryNode和Leaf而不是传入的node值有关。

//Call
query_area = new a2de::Rectangle(_mouse->GetX(), _mouse->GetY(), 100.0, 100.0, a2de::YELLOW, false);
_selected_elements = _qt->Query(*query_area);

//...
//Definitions
template<typename T>
std::vector<T> QuadTree<T>::Query(const a2de::Shape& area) {
    std::vector<T> selected_elements;
    QueryNode(this, area, selected_elements);
    return selected_elements;
}

template<typename T>
void QuadTree<T>::QueryNode(QuadTree<T>* node, const a2de::Shape& area, std::vector<T>& selected_elements) {

    if(node == nullptr) return;

    if(node->_bounds.Intersects(area) == false) return;

    if(IsLeaf(node)) {
        for(std::vector<T>::iterator _iter = node->_elements.begin(); _iter != node->_elements.end(); ++_iter) {
            selected_elements.push_back(*_iter);
        }
        return;
    }
    for(std::size_t i = 0; i < MAX_CHILDREN; ++i) {
        QueryNode(node->_children[i], area, selected_elements);
    }
}