Solved

C++ Fill the missing gaps...

Posted on 2010-11-11
21
760 Views
Last Modified: 2012-05-10
Hello.

I have to fill in the missing gaps for this program...


#include <iostream>

using namespace std;

template<class T>

class Stack

{

public:

      Stack(int s = 100) : size(s), top(-1) { data = new T[size]; };

      ~Stack() {------; };

      void push(const T& x) { data[----] = x; };

      T pop() { return data[-----]; };

      int isEmpty() const { return --------; };

      int isFull() const { return ----------; };

private:

      int size;

      int top;

      T* data;

};


int main()

      {

            Stack<int> intStackl(5);

            Stack<int> intStack2(10);

            Stack<char> charStack(8);

            intStackl.push(77);

            charStack.push('A');

intStack2.push(22);

            charStack.push('E');

  charStack.push('K');

intStack2.push(44);

            cout << intStack2.pop() << endl;

            cout << intStack2.pop() << endl;

            if (intStack2.isEmpty()) cout << "intStack2 is empty.\n";

            system("pause");

            return 0;
      }

Open in new window


I have done this will the code bellow

#include <iostream>

using namespace std;

template<class T>

class Stack

{

public:

      Stack(int s = 100) : size(s), top(-1) { data = new T[size]; };
      ~Stack() {};

      void push(const T& x) { data[size] = x; };

      T pop() { return *data;};

      int isEmpty() const { return data[size]; };
      int isFull() const { return data[size]; };

private:

      int size;
      int top;
      T* data;

};

      int main()

      {

            Stack<int> intStackl(5);
            Stack<int> intStack2(10);
         
            intStackl.push(77);        
			intStack2.push(22);
			intStack2.push(44);


            cout << intStack2.pop() << endl;
            cout << intStack2.pop() << endl;

            if (intStack2.isEmpty()) cout << "intStack2 is empty.\n";

            system("pause");

            return 0;

      }

Open in new window


The answer I get is...

-842150451
-842150451
intStack2 is empty.
Press any key to continue . . .

I am not sure that this is correct and that it is looking for the address...

Can anyone see where I went wrong if I did?

- Thanks
0
Comment
Question by:ibax
  • 11
  • 4
  • 4
21 Comments
 
LVL 32

Expert Comment

by:phoffric
ID: 34113312
A quick look, and I see that you are not using top, and that for isEmpty(), you are returning data rather than something that indicates whether the stack is empty.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34113338
For the stack, you may wish to consider using vector rather than an array. I see that you are using new [], but I don't see you using delete [].
0
 
LVL 40

Accepted Solution

by:
evilrix earned 250 total points
ID: 34113477
Some observations...


* The destructor needs to delete data.

* Push is always going to add at position "size", should it not be whatever the postion is of the stack pointer?

* Since push is adding to the back pop should be removing from the back (otherwise it's a queue). Also not this code is note exception safe but I don't know if that is an issue -- it returns by value and a copy constructor can throw so you will lose the item that was popped.

* isEmpty should return true if the stack had items in it... it's just returning the back element.

* isFull, same as isEmpty.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34113480
Converting -842150451 to hex, you get 0xCDCDCDCD.When you build your program in debug mode, this means that the data is not initialized. Take a close look at how you are setting the array (stack) value, and you should see the error.    
0
 
LVL 32

Assisted Solution

by:phoffric
phoffric earned 250 total points
ID: 34113573
So, in your constructor, you set size to 10 and create an array of 10 elements. And your push is doing    data[size] = x;i.e.,   data[10] = x;Now, you probably know that if you create an array of 10 elements, the the valid indexes are 0..9 (so that is a serious error since you are setting an array location that is outside of the allocated region - this error could cause a segmentation fault crash).But, then your pop() returns *data which is pointing to the first element, which, as mentioned earlier, is not being set by your push.
0
 

Author Comment

by:ibax
ID: 34113613
Thanks for the continued comments guys, Just trying to figure it out now.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34113907
In general, if you use a debugger, it will save you many hours of debugging. I use Visual Studio 2008 C++ debugger for Windows and ddd for Cygwin. Here's an article to get you started with VS debugger:    http://w.e-e.com/0XEBxvIf you have any questions on using it, don't hesitate to ask.Here's debugger information for the ddd GUI debugger (which you may need to install on Linux in addition to gdb and Xming, if you haven't done so already).    http://heather.cs.ucdavis.edu/~matloff/Debug/Debug.pdf    http://www.gnu.org/manual/ddd/html_mono/ddd.html        
0
 

Author Comment

by:ibax
ID: 34113969
Thankyou.

Should the end product product all the values that were pushed in order?

intStackl.push(77);

charStack.push('A');

intStack2.push(22);

charStack.push('E');

charStack.push('K');

ntStack2.push(44);
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34114012
BTW - I see that isEmpty() is returning an int. If you were handed the class and told to fill in the gaps, then that is fine, and useful for your own knowledge since many programmers in industry do it that way. What you may already know is that in the if-expression    if( isEmpty() )if isEmpty returns 0, then that is treated as false, and if it returns any integer != 0, then that is true.But, for the purposes of more robust coding, some of my projects required us to make our own enum boolean types having different patterns, say 0xFBAD for false and 0xDEED for true (or anything you prefer). When using this style, we were required to do:
   if( prjTRUE == isEmpty() ) {

      // ...

   }

   else if ( prjFALSE == isEmpty() ) {

      // ...

   }

   else {

       // system failure recovery code goes here!

   }

Open in new window

0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 32

Expert Comment

by:phoffric
ID: 34114035
>> Should the end product product all the values that were pushed in order?A stack is a LIFO (last in - first out) container.If you push 1, 2, 3then the stack looks like:3 <- top21Then when you pop the stack the first time, the last item you pushed (i.e., 3) get popped off the stack, and now the stack should look like:21
0
 

Author Comment

by:ibax
ID: 34114305
     void push(const T& x)
        {
              data[---------] = x;
        };


How do I use push to add the elements to the top in this function.

If anything the only thing that is printed is the last value that is 44 and it's not adding to the stack by the looks of it.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34114368
In your stack class, you have size which represents the amount of allocated memory for the stack. Every time you push an element onto the stack, it would be useful to have a count of the number of items on the stack.

Initially count is 0, of course. Since you are returning an int for isEmpty(), then returning "count" would correspond to 0 for false, and not 0 for true.

Given that you are using an array (and I assume that you may need this array to grow if more items are added than the initial allocation, then the first item is at index [0]. Using the count attribute, you can push the new element into the correct spot (just be careful with indexing).
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34114393
I forgot my initial comment:
>> A quick look, and I see that you are not using top
This "top" corresponds to the "count". So, if you use "top", then you should be OK, and the "count" is redundant. But you will have to be careful in what isEmpty() returns, and with the indexing.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34114421
In previous post, I said:

If you push 1, 2, 3
then the stack looks like:
3 <- top
2
1

What you have to do is ask, what are the indexes into my stack array for these three elements? You can let me know what you think.
0
 

Author Closing Comment

by:ibax
ID: 34114942
Thanks for the help.
0
 
LVL 40

Expert Comment

by:evilrix
ID: 34119221
Were none of the things I pointed out even remotely useful? I pretty much identified the issues you were having plus some additional ones too.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34122869
If you wish, you can Request Attention, reopen, and select multiple posts and re-assign points for all posts which you found useful.
   Cheers,
       phoffric
0
 
LVL 40

Expert Comment

by:evilrix
ID: 34123074
Oops, I didn't mean to post the last post as an admin comment - it seems this weeks release has changed my default comment type to admin :(

I've removed the admin'ness!
0
 
LVL 40

Expert Comment

by:evilrix
ID: 34125234
Recommendation for closure is as follows.

http:#34113477 - identified the main issues (and a couple others)
http:#34113573 - explained the main issue in detail

Other posts by Paul were also extremely helpful but these two together identify the issues observed in the question.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now