Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector vs std::stack

What is the difference between std::vector and std::stack?

Obviously vectors can delete items within the collection (albeit much slower than list) whereas the stack is built to be a LIFO-only collection.

However, are stacks faster for end-item manipulation? Is it a linked list or dynamically re-allocated array?

I can't find much information about stacks, but if I'm picturing them correctly (they are similar to an actual thread stack; push, pop, etc. - along with that top() method) then they seem perfect for window-stacking management.

like image 510
Qix - MONICA WAS MISTREATED Avatar asked Sep 18 '12 23:09

Qix - MONICA WAS MISTREATED


People also ask

Is std::vector on the stack?

Although std::vector can be used as a dynamic array, it can also be used as a stack.

What is the difference between vector and stack in C++?

stack is a stack. It can only push and pop. A vector can do other things, like insert into the middle. This increases flexibility, but reduces guarantees.

Which is faster stack or vector?

vector will outperform list for almost every use case.

Is std::vector on heap or stack?

std::vector typically allocates memory on the heap (unless you override this behavior with your own allocator). The std::vector class abstracts memory management, as it grows and shrinks automatically if elements are added or removed.


1 Answers

A stack is not a container; it is a container adapter. It has a vector, deque or similar container that it stores as a member that actually holds the elements. Remember: it is declared as:

template<
    class T,
    class Container = std::deque<T>
> class stack;

All stack does is limit the user interface to this internal container. The performance characteristics of the operations are exactly whatever the underlying container's performance characteristics are.

like image 98
Nicol Bolas Avatar answered Oct 21 '22 02:10

Nicol Bolas