Sign in to follow this  
Thetan

Why use container adaptors?

Recommended Posts

Why would anyone use a container adapter such as stack or queue instead of just using the base container alone? Is the only gain a simplified interface? Thanks in advance

Share this post


Link to post
Share on other sites
There are plenty of cases where a stack or queue is appropriate. If you use just the base container instead, then you must create your own version of a stack or queue. Why would anyone waste time creating their own version when one already exists?

Share this post


Link to post
Share on other sites
Algorithms are often defined using specific structures.

Although the underlying implementations are similar, or share majority of code, the interface to it is unsuitable.

So these are merely convenience interfaces that balance code re-use and straight-forward interface.

The performance penalty is a non-issue, if that's what one of your concerns was.

Share this post


Link to post
Share on other sites
Quote:
Original post by JohnBolton
If you use just the base container instead, then you must create your own version of a stack or queue. Why would anyone waste time creating their own version when one already exists?

Maybe I'm missing something, but why would you have to create your own version? Everything you would be able to do with a std::stack<int, std::vector<int>> you can do right out of the box with a simple std::vector<int>.

Performance never was a concern for me, because I'm aware of the STL's awesome inlining.

I just want to know if there are more benefits to using container adapters other then typing .push() instead of .push_back() etc.

Thanks Antheus

Share this post


Link to post
Share on other sites
Quote:
Original post by Thetan

I just want to know if there are more benefits to using container adapters other then typing .push() instead of .push_back() etc.


These structures go back to elementary data structures.

A stack for example defines push(), pop(), empty() and top() operations. There could be one I missed.

If you use a vector, you can add elements in middle, remove elements from anywhere, and so on.

This is the same reason why using raw pointers is bad. Sure, it's possible to cast void * to MyMultiplyInheritedObject *. But there's a reason why it's strongly discouraged.

A stack is a stack. Nothing more and nothing less. Same for all other structures.

The only benefit you get is code clarity, and some additional safety. If you provide user with a vector, they'll do funny stuff, even if you state in comments that vector represents a stack. But if you return stack, then they can't break it.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this