【问题标题】:Storing and retrieving a structure on a queue在队列中存储和检索结构
【发布时间】:2015-07-29 16:43:57
【问题描述】:
void addElement(struct BinaryTree *root, int data) {
    if (!root)
        return;
    BinaryTree *newNode = new BinaryTree;
    newNode->data = data;
    newNode->right = NULL;
    newNode->left = NULL;
    queue<BinaryTree> *myqueue = new queue<BinaryTree>;
    myqueue->push(*root); // Why do i have to dereference the object to store it in the queue;
    BinaryTree *temp;
    while (!myqueue->empty()) {
        temp = myqueue->front()
        //Throwing an error

        myqueue->pop();
        if (temp->left) {
            myqueue->push(*temp->left);

        } else {
            temp->left = newNode;
            break;
        }
        if (temp->right) {
            myqueue->push(*temp->right);
        } else {
            temp->right = newNode;
            break;
        }

    }
}

【问题讨论】:

  • C++ 不是 Java,您不必动态分配所有对象。您的队列对象不必是指针并动态分配,它可能导致指针问题和内存泄漏(您有)。而是将其定义为普通的非指针对象std::queue&lt;BinaryTree&gt; myqueue;
  • 至于解引用,与root的类型相比,考虑一下存储在队列中的类型。此外,这种混淆是代码无法编译的原因。

标签: c++ struct queue


【解决方案1】:

myqueue->push(*root); // 为什么我必须取消引用对象才能将其存储在队列中;

这是因为你的队列模板是用BinaryTree 类型实例化的,它不是一个指针,所以你不能在它里面放入BinaryTree *root 类型的变量。您必须使用 *root 取消引用它。

如果你有queue&lt;BinaryTree*&gt;,那么你可以使用myqueue-&gt;push(root);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 1970-01-01
    • 2012-06-14
    相关资源
    最近更新 更多