Hi, I have a homework assignment to copy the elements of one stack to the other except in reverse order. The algorithm is easy enough for me to figure out and implement. My only question is, I dont really understand how im supposed to add my own function to a STL Stack class. AKA, stack already has pop, push, etc. I want to add my own reverse function. Can anyone help me get started? Thanks

Edit: Or should I just write a seperate function that takes two stack's as arguments and does everything on its own?

Hi, I have a homework assignment to copy the elements of one stack to the other except in reverse order. The algorithm is easy enough for me to figure out and implement. My only question is, I dont really understand how im supposed to add my own function to a STL Stack class. AKA, stack already has pop, push, etc. I want to add my own reverse function. Can anyone help me get started? Thanks

Edit: Or should I just write a seperate function that takes two stack's as arguments and does everything on its own?

Create your own class that holds an STL stack as a data member that you can modify. Write stuff such as a pop() function on your class that will just pop from the stl stack. Therefore you can write a reverse function that just reverses the stl stack you are holding as a data member.

So I dont need to inherit or anything then? Also, how are you supposed to reverse a LIFO Data Structure?

I started working on some stuff without createing my own class, but am obviously doing the reverse function wrong. And also, I would like to learn it the proper way by creating my own class. So any examples to help get me started is much appreciated.

#include <stack>
#include <iostream>

using namespace std;

void copyReverse(stack<int> &, stack<int> &);

int main()
{
	stack<int> stack1;
	stack<int> stack2;

	int num = 0;

	while(num != -999)
	{
		cout << "\nPush:";
		cin >> num;

		stack1.push(num);
	}

	copyReverse(stack1, stack2);

	
	cin.ignore();
	cin.get();

	return 0;
}

void copyReverse(stack<int> &stk1, stack<int> &stk2)
{
	while(!stk1.empty())
	{
		stk2.push(stk1.top());
		stk1.pop();
	}
       //Print out in reverse, but its still in the same order because push puts it at the end of the stack.

	while(!stk2.empty())
	{
		cout << stk2.top() << endl;
		stk2.pop();
	}




}

Anybody?

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.