Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using stack defined in C++ stl

Tags:

c++

stack

stl

#include <stack>
using namespace std;

int main() {
    stack<int> s;
    int i;
    for (i = 0; i <= 10; i++) {
        s.push(i);
    }
    for (i = 0; i <= 10; i++) {
        printf("%d", s.pop());
    }
}

Whats wrong with the code above?

Error:

In function int main(): aggregate value used where an integer was expected

like image 618
Moeb Avatar asked Apr 11 '10 11:04

Moeb


2 Answers

stack::pop is a void function which just discards the top element on the stack, in order to get the value you want to use stack::top.

The reason this is so is for exception safety reasons (what happens if the object returned throws an exception in its copy constructor?).

like image 136
Motti Avatar answered Sep 28 '22 09:09

Motti


Minor nitpick, your for loop is actually encoding 11 items and not 10 like you make think from a brief look at the loop count. Consider using < 11 if you mean 11 elements to add.

like image 24
Michael Dorgan Avatar answered Sep 28 '22 09:09

Michael Dorgan