What are the differences between them? And in what cases it is preferable to use one or another data structure?
3 answers
Ideologically, the difference is that only a vertex is available for operations in a stack, and a vector is a random access structure, i.e. At any time you can access any item.
As for the implementation, then often the stack is just an adapter of some container. The same vector can act as an adapter.
KO says that it is preferable to use the stack when you need ... a stack, i.e. LIFO structure (last in, first out). For example, the well-known "Polish notation" is implemented on the basis of the stack.
It seems to me that the stack is widely implemented in programming and is used when exiting nested loops and nested function calls.
"Antagonist" stack - turn.
https://stackoverflow.com/questions/12486487/stdvector-vs-stdstack
stack is not a container, but an adapter . It uses vector, deque (default) or another container with a suitable interface that stores the elements. Remember: stack is defined as:
template< class T, class Container = std::deque<T> > class stack; All that stack does is limit the interface for the used container. The performance of operations is fully determined by the properties of the container used.
In a more general case: you can use in your own implementation of the stack "algorithms and data structure" optimized for the fact that you only need access to the top of the stack, and access to an arbitrary element by index is not available, or scanning (searching or filtering), and get a gain on memory / speed.
std::stackandstd::vectorin C ++? If the first, what does the [C ++] tag do here? If the second, then the question, to put it mildly, is meaningless: in C ++, these are entities of different "order" - an adapter and a container - and comparing them directly is how to compare a cow and a triangle. - AnT