gpt4 book ai didi

c++ - std vector 、堆栈和队列中的原始指针

转载 作者:太空宇宙 更新时间:2023-11-04 06:00:40 25 4
gpt4 key购买 nike

我对二叉树有以下问题:

....

模板
类二叉树
{
私有(private)的:
模板
结构节点
{
T值;
左节点*;
节点*对;
};
私有(private)的:
节点*根;



std::stack
    
     const *> 堆栈;
     

堆栈。推(根);

而(假==堆栈。空())
{
节点 * 节点 = stack.pop();

这个->已访问(节点->值);

之后,当我尝试实现呼吸优先搜索时:模板 类二叉树 { 私有(private)的: 模板 结构节点 { T值; 左节点*; 节点*对; }; 私有(private)的: 节点*根;

std::stack<Node<T>const *> stack;

stack.push(root);

while(false == stack.empty())
{
Node<T>* node = stack.pop();

this->visited(node->value);

我收到一个错误:

错误 4 error C2440: 'initializing' : cannot convert from 'void' to 'BinaryTree::Node *' c:\users\stephan\documents\visual studio 2012\projects\graphs\binarytree\binarytree.cpp 152 1二叉树

最佳答案

问题出在这里:

Node<T>*  node = stack.pop();

pop()删除元素并返回 void。使用 top()事先。

Node<T>*  node = stack.top();
stack.pop();

原文STL documentation解释这种设计背后的原因:

One might wonder why pop() returns void, instead of value_type. That is, why must one use top() and pop() to examine and remove the top element, instead of combining the two in a single member function? In fact, there is a good reason for this design. If pop() returned the top element, it would have to return by value rather than by reference: return by reference would create a dangling pointer. Return by value, however, is inefficient: it involves at least one redundant copy constructor call. Since it is impossible for pop() to return a value in such a way as to be both efficient and correct, it is more sensible for it to return no value at all and to require clients to use top() to inspect the value at the top of the stack.

关于c++ - std vector 、堆栈和队列中的原始指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19883022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com