Using stack defined in C++ stl

2019-06-22 07:46发布

#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

标签: c++ stl stack
3条回答
闹够了就滚
2楼-- · 2019-06-22 08:37

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?).

查看更多
我想做一个坏孩纸
3楼-- · 2019-06-22 08:44

You're treating pop() which is an operation to print to standard output. pop() just removes the topmost element from the stack. The most confusing thing however is your debug output.

I compiled your code fragment with the standard GNU C++ compiler which gave me:

main.cpp|12|error: invalid use of void expression

int main() {
    stack<int> s;
    int i;
    for (i = 0; i <= 10; i++) {
        s.push(i);
    }
    for (i = 0; i <= 10; i++) {
          printf("%i", s.top());
          s.pop();
    }
}
查看更多
我命由我不由天
4楼-- · 2019-06-22 08:53

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.

查看更多
登录 后发表回答