alfablac
alfablac

Reputation: 55

Error using vector as container adaptor for stack

I can't make things work out with container adaptors of the class stack on STL. Here's the code:

typedef stack <int, vector<int> > vector_stack;

...

int main()
{
    vector_stack vec;

    vec.push(10);
    vec.push_back(20);
    vec.push_back(30);
    vec.pop();
    cout << vec[0] << vec[1];

    ...

}

It passes through .push(10) as expected because it's a stack member function, but .push_back as a vector member function it doesn't accept. The error is:

'class std::stack<int, std::vector<int> >' has no member named 'push_back'

Upvotes: 0

Views: 313

Answers (2)

ravi
ravi

Reputation: 10733

Stack is container adapter i.e simply an interface to a container of the type passes to it as a template argument. All stack does is to eliminate the non-stack operations on its container from the interface and give back(), push_back() and pop_back() their conventional names top(), push() and pop()

Also, by default stack makes a deque to hold its elements but any sequence that provides back(), push_back() and pop_back() can be used.

Upvotes: 0

Neil Kirk
Neil Kirk

Reputation: 21793

push_back is not a member of std::stack, even though it's a member of the underlying container type. That's just the way it's defined. You must use push.

If you want a "vector stack" personally I would use std::vector directly, but that's just my opinion.

Upvotes: 2

Related Questions