Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the major difference between a vector and a stack?

Both act like a stack. Both have push and pop operations.

Is the difference in some memory layouts?

like image 657
Aquarius_Girl Avatar asked Jan 09 '12 08:01

Aquarius_Girl


People also ask

Which is faster vector or stack?

Practically, no. vector will outperform list for almost every use case.

What is the difference between stack and array?

A stack is a type of linear data structure that is represented by a collection of pieces that are arranged in a predetermined sequence. An array is a collection of data values that are associated to one another and termed elements.

Can you use a vector as a stack?

Stack behavior with std::vector Although std::vector can be used as a dynamic array, it can also be used as a stack. To do this, we can use 3 functions that match our key stack operations: push_back() pushes an element on the stack.


2 Answers

std::vector has several accessibility and modification operations compared to std::stack. In case of std::stack, you may have to perform operations only in systematic way, where you can push() above the last element or pop() the last element.

std::vector is more flexible in that sense, where it has several operations, where you can insert() in between or erase() in between.

The major point is that, std::stack needs to be provided the underlying container. By default it's std::deque, but it can be std::vector or std::list too.
On other hand, std::vector is guaranteed to be a contiguous array which can be accessed using operator [].

like image 158
iammilind Avatar answered Oct 12 '22 08:10

iammilind


I'm not aware of all the implementation details, but according to this, stack is a container adaptor. It makes sure the underlying container, which can be a vector, list or deque, works as a stack, i.e. only allows push and pop, and not random access.

So, a vector can work as a stack, but a stack cannot work as a vector, because you cannot insert or get an element at a random position.

like image 27
MikMik Avatar answered Oct 12 '22 10:10

MikMik