C++无法在堆栈中使用peek()函数

C++ unable to use peek() function in stack

本文关键字:peek 函数 堆栈 C++      更新时间:2023-10-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":不是"std::stack&lt_Ty>'

我做错了什么?

我想你想使用

s.top();

而不是峰值。

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();
        }
    }
}

std::stack中没有peek函数。有关参考,请参阅堆栈

看起来你正在使用top的功能。要获得顶部的参考,请查看此参考。

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