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

前端 未结 6 777
不思量自难忘°
不思量自难忘° 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:14

    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 [].

提交回复
热议问题