0

我有结构:

struct node
{
    bool data;
    node* l;
    node* r;
    node(bool data_) : data(data_), l(0), r(0) {}
};

像这样循环

void printNode(std::vector<node*> nodes, int level, int max_level)
{
    for (int i = 0; i < nodes.size(); i++) {
        node * itr = nodes.at(i);
        if (itr->data != 2) {
            cout << itr->data;
            newNodes.push_back(itr->l);
            newNodes.push_back(itr->r);
        } else {
            newNodes.push_back(new node(2));
            newNodes.push_back(new node(2));
            cout << " ";
        }

        printWhitespaces(betweenSpaces);
    }
}

有时 itr->l(or r) 为空,而不是 init 结构。我怎样才能检查这个?

4

2 回答 2

1

Something like this? It will skip your NULL elements, and elements with NULL value for r member of the vector and continue the for loop.

node * itr = nodes.at(i);
if(!itr || !itr->r) continue;
于 2012-12-21T02:13:42.897 回答
0

要检查指针是否为空,只需使用:

itr->l == 0

如果为 0,则为空。但是考虑使用智能指针,它们更安全。

您还应该考虑使用以下方法以标准方式迭代您的向量:

std::vectoc<node*>::iterator
    it = nodes.begin(),
    ite = nodes.end();
for(; it != ite; ++it) {
    ...
}

最后你可能应该像这样通过引用传递你的向量:

void printNode(std::vector<node*>& nodes, int level, int max_level)
于 2012-12-21T02:16:27.777 回答