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

前端 未结 6 773
不思量自难忘°
不思量自难忘° 2021-01-31 18:29

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

Is the difference in some memory layouts?

6条回答
  •  抹茶落季
    2021-01-31 19:04

    As cplusplus.com suggests:

    Stacks are a type of container adaptor, specifically designed to operate in a LIFO context (last-in first-out), where elements are inserted and extracted only from one end of the container.

    The key word here is only, as in elements are only inserted and extracted from one end of the container.

    You say both vectors and stacks act like stacks, but this is only partially true. Vectors can act like stacks, but they can also act very much not like stacks, by allowing you to do things such as insert at any index, access any element, iterate over the entire structure, etc.

    Stacks take a container (such as, for example, a vector) and only permit stack-like interactions with it. This effectively guarantees that all interactions with the container will obey LIFO: only the most recently added element in the container will be able to be accessed or removed.

    If you want a container with stack-like behavior, you should use a stack if it is particularly important to you that it behaves exclusively a stack. You should use a vector if you want stack-like behavior but might also want to do things like iterate over elements or modify elements in arbitrary positions etc.

提交回复
热议问题