【问题标题】:C++ unable to use peek() function in stackC++ 无法在堆栈中使用 peek() 函数
【发布时间】:2012-04-14 14:02:16
【问题描述】:

我正在尝试将 Visual Studio 2010 中的 peek 函数与这些库一起使用:

#include "stdafx.h"
#include <string>
#include <string.h>
#include <fstream>
#include <iostream>
#include <string.h>
#include <vector>
#include <stack>

但是,我不能在堆栈中使用peek 函数:

void dfs(){
    stack<Node> s;
    s.push(nodeArr[root]);
    nodeArr[root].setVisited();
    nodeArr[root].print();
    while(!s.empty()){
        //peek yok?!
        Node n=s.peek();        
        if(!n.below->isVisited()){
            n.below->setVisited();
            n.below->print();
            s.push(*n.below);
        }
        else{
            s.pop();
        }
    }
}

我得到错误:

错误 1 ​​错误 C2039: 'peek' : is not a member of 'std::stack<_ty>'

我做错了什么?

【问题讨论】:

标签: c++ stack peek


【解决方案1】:

我想你想用

s.top();

而不是峰值。

【讨论】:

    【解决方案2】:

    std::stack 中没有 peek 函数。

    你在找top()吗?

    void dfs(){
        stack<Node> s;
        s.push(nodeArr[root]);
        nodeArr[root].setVisited();
        nodeArr[root].print();
        while(!s.empty()){
            //peek yok?!
            Node n=s.top();   // <-- top here
            if(!n.below->isVisited()){
                n.below->setVisited();
                n.below->print();
                s.push(*n.below);
            }
            else{
                s.pop();
            }
        }
    }
    

    【讨论】:

    • 非常感谢大家。在 msdn 中,当我看到对 peek 的引用时,我想我是真的。但你是对的,我错了。再次感谢您的回复。
    【解决方案3】:

    std::stack 中没有 peek 函数。参考请见stack

    看起来您正在使用top 的功能。如需顶部参考,请查看this reference

    【讨论】:

      【解决方案4】:

      您的代码有stack,但您实际上想使用Stack。他们是两个不同的东西。

      【讨论】:

      猜你喜欢
      • 2021-01-14
      • 2021-08-04
      • 1970-01-01
      • 2021-01-30
      • 2013-02-25
      • 2016-10-24
      • 2012-10-30
      • 1970-01-01
      • 2012-08-26
      相关资源
      最近更新 更多