is it possible to have a back() in stack....i know queue and vector has it...

#include "Card.hpp"
#include "Card2.hpp"
#include <stack>

using namespace std;
typedef char StackItemType;

bool Card::isEmpty() const {
	return cards.size() == 0;
}

Card Card::see() const {
	return cards.back();
}

Card Card::pop() {
	Card c = cards.back();
	cards.pop_back();
	return c;
}

void Card::push( const Card& c ) {
	cards.push_back( c );
}

int Card::size() const {
	return cards.size();

thank u for ur help...

Recommended Answers

All 3 Replies

If you think about the abstraction of the data structure, it doesn't make sense to. It is a last in/first out (LIFO) system. If you need a queue or even a deque, then you should use those data structures instead.

is it possible to have a back() in stack....i know queue and vector has it...

For the standard container adapter, no. Check any reference and you'll see that the exposed non-boilerplate methods are push(), pop(), top(), and empty(). However, std::stack is an adapter for an existing container (the default is std::deque). If you need more control, simply use the underlying container directly rather than the adapter.

If you think about the abstraction of the data structure, it doesn't make sense to.

On a high level design note, if you have a strict abstraction (just push and pop) then it's not as useful as it could be. Here are some handy dandy stack operations that don't always fit easily into the strict abstraction:

  • Retrieve the top item without popping it.
  • Duplicate the top item.
  • Swap the first and second item.
  • Rotate the top three items.
  • Copy the second item and push it to the top.
  • Copy the top item and insert it underneath the second item.

Not that I'm suggesting a stack library should implement these (or others), but it's important to recognize that as a library author, you don't have to conform to strict data structure definitions if extending them makes the library more useful to your target audience.

Forth is a good example of a stack based language that extends the abstraction in simple yet useful ways.

commented: Thanks! +14

have to conform to strict data structure definitions

If your abstraction is strictly a LIFO stack, then the code should adhere to that. If your abstraction is the stack with the features you've described, then sure, have a party. It's whether you call a duck a duck. Once you propose a queue with a magic viewing window in the middle, you're not really after a queue anymore.

I do, however, understand the practicality of what you are saying.

Forth is a good example

I've never braved Forth :) I'm still stuck on Thurd.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.