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

Saliha Uzel picture Saliha Uzel · Mar 30, 2012 · Viewed 16.4k times · Source

I am trying to use the peek function in Visual Studio 2010 with these libraries:

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

However, I cannot use the peek function in the stack:

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

I get the error:

Error 1 error C2039: 'peek' : is not a member of 'std::stack<_Ty>'

What am I doing wrong?

Answer

Jarosław Gomułka picture Jarosław Gomułka · Mar 30, 2012

I think you want to use

s.top();

instead of peak.