Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the advantages and disadvantages of using std::stack instead of just deque, vector or list

I am writing a very simple std::stack using vector as its underlying container. I realized that I could replace all the push(), pop() and top() functions with push_back(), pop_back() and back() of the vector container.

My questions are: why to use a container adaptor when the controlled use of the underlying container is enough? Why not to use just a deque, vector or list? There will be waste of memory or processing time?

like image 617
pbruno Avatar asked Jan 29 '15 04:01

pbruno


1 Answers

When your code says std::stack it's clear to the reader what operations they need on the container... it communicates and documents while enforcing that no other operations are used. It may help them quickly form an impression of the algorithmic logic in your code. It's then easy to substitute other implementations that honour the same interface.

It's a bit like using std::ifstream instead of std::fstream - you can read and write with std::fstream, but whomever reads your code will need to consider more possible uses you put the stream to before realising that it's only being used for reading; you'd be wasting their mental effort.

like image 78
Tony Delroy Avatar answered Sep 17 '22 04:09

Tony Delroy