Solved

Stack template Question

Posted on 2001-08-26
8
574 Views
Last Modified: 2008-02-01
#include <iostream.h>
#include <string.h>
#include "STACK.cpp"

int main(int argc, char *argv[])
  { char *a = argv[1]; int N = strlen(a);
    STACK<char> ops(N);
    for (int i = 0; i < N; i++)
      {
        if (a[i] == ')')
          cout << ops.pop() << " ";
        if ((a[i] == '+') || (a[i] == '*'))
          ops.push(a[i]);
        if ((a[i] >= '0') && (a[i] <= '9'))
          cout << a[i] << " ";
      }
    cout << endl;
     return 0;
  }      

In this stack example client file of infix to postfix, What is the syntax for the
top item on the stack. I am trying to make the implementation file and the
constructor sshould have the topitem = -1 but I can't see where it is
using a template.
Is this the constructor?
STACK::STACK
{
TopItem = -1;//I am not sure what the syntax is in the client file?
Is this header correct for this client file?

}

//Header

template <class Item>
class STACK
  {
    private:
      // Implementation-dependent code
    public:
      STACK(int);
      int empty() const;
      void push(Item item);
      Item pop();
0
Comment
Question by:Andy36
  • 5
  • 3
8 Comments
 
LVL 22

Accepted Solution

by:
nietod earned 40 total points
ID: 6426463
>> What is the syntax for the
>> top item on the stack
To retreive the top item use code like

char TopItem = ops.pop();

>> but I can't see where it is
>> using a template.
Well, you posted almost none of the relevant code.  you didn't post stack.cpp for example.  But fromw hat little bit you did post, it looks like you are using a template.  the code

>> template <class Item>
>> class STACK

which declares stack as a template class.

When you create ops as an instance of this class you have

>>  STACK<char> ops(N);

which declares an instance of the template specialized for the char data type.  

>> Is this the constructor?
>> STACK::STACK
Yes, but it hass to have parenthesis like

   STACK::STACK()
   {
       *  *  *
   }

>> Is this header correct for this client file?
How could we tell?  You haven't psoted it!

What's more, you aren't including a header for this class in your program.  You are including "stack.cpp" not "stack.h".  While that can be made to work, its very unusual.  You should have a stack.h that you include instead.  

We really need to see ALL the code.  with a clear indication of what is in each file.
0
 
LVL 22

Expert Comment

by:nietod
ID: 6426484
Note that the file <iostream.h> should be <iostream>.  I have a prepared commend about this.

*****************************************

The official STL (Standard Template Library) files are all extensionless files, like <iostream>, <vector>, and <list>.  You may find that your compiler has files with these names but a .h extension, like <iostream.h>, <vector.h>, and <list.h> but these are not the standard files.  These files are old, non-standard files that are provided for compativbility for old programs that used them before the standard files were settled upon.  You want to avoid usign this files if you have the standard ones availalbe.  The non-stnadard files may not have all the features of the standard ones, they also likely to have more bugs and other problems, and also since they are not standardized, they will varry from compiler to compiler, and might not even exist on many compilers.  So avoid using these files if you have the extenionless, standardized files.

Now there is one big difference between the standardized files and many of the non-standardized files.  The standardized files place all of their symbolic names in the "std" namespaces.  This is so that the names defined in these files don't clash with names you write in your program.  So in order to access the names inside the standard STL files you need to prefix them with "std::" like

std::vector<std::string> StringArray;

If you do not wish to use those "std::",  you can instead add a using directive like

using namespace std;

after you include the STL  include files.  Then these names will all be brought into your namespace.
0
 

Author Comment

by:Andy36
ID: 6426585
I do not have a implementation file written. I am trying to figure out with the client file example and the header what is the syntax for the TopItem. What is the TopItem called in the client file or the header file. Do I need a header file when I use a template? Here is the code I have so far:

#include <iostream>
#include <string>
#include "STACK.cpp"
#include "stack.h"

using namespace std;

int main(int argc, char *argv[])
  { char *a = argv[1]; int N = strlen(a);
    STACK<char> ops(N);
    for (int i = 0; i < N; i++)
      {
        if (a[i] == ')')
          cout << ops.pop() << " ";
        if ((a[i] == '+') || (a[i] == '*'))
          ops.push(a[i]);
        if ((a[i] >= '0') && (a[i] <= '9'))
          cout << a[i] << " ";
      }
    cout << endl;
     return 0;
  }      

Implementation

#include "stack.h"

STACK::STACK()
{
//I do not know what the TopItem is being called


}

template <class Item>
class STACK
  {
    private:
      // Implementation-dependent code
    public:
      STACK(int);
      int empty() const;
      void push(Item item);
      Item pop();
  };

I am also not sure what these variables are doing?
(int argc, char *argv[]) under int main?

0
 
LVL 22

Expert Comment

by:nietod
ID: 6426875
>> what is the syntax for the TopItem
What does that mean?   You can ask for the syntax to perform an action.  Or the syntax to declare something.  But "TopItem" does not sound like either.  You want the syntax for ... what?

>> What is the TopItem called in the client
>> file or the header file
What do you mean by "TopItem"?

>> Do I need a header file when I
>> use a template?
You never HAVE to use a header file for anything.

But if you have code that you want to use in more than one source code file, then it is a good idea to put that code in a header file.  So for example, if you want to use this stack class from more than one source code file, you might want to place its declaration in a header file so that you can include that header file in any source code file that needs it.  you don't have to, but that is easier than retyping the code into every source code file that needs it.

Note that most compilers will require that the entire template definition, including its member fucntions to be included in the source code when you use a class template.  This means that the definitions for the template class's member functions must also be placed in the .h file too.  (The C++ langauge does not require this, you can use the "export" keyword to indicate that a tempalte class's definition is in a seperate file, but most compilers don't yet support this feature.

>> #include "STACK.cpp"
>> #include "stack.h"
Why both?
What is in stack.cpp?
What is in stack.h?

>> //I do not know what the TopItem
>> is being called
What do you mean?  There isn't going to be some member called "TopItem"?  right?  The stack has to store potentially many items.  How these are being stored depends on how the stack was written.  Since you ahven't really posted the code for that, i can't help you there.

>>    private:
>>   // Implementation-dependent code
Are you supposed to be writting this stakc class?  It doesn't look like it was written completely.

>> (int argc, char *argv[]) under int main?
These are the standard parameters passed to main().  

argc is the number of parameters that are passed to the program.  The first parameter is always the name of the program or the command used to run the program.  So argc is always at least 1, but it will be more than 1 if there were additional parameters.

argv is an array of pointers.  The number of pointers in the array is specified by argc.  Each pointer points to a NUL termianted string that specifies a parameter passed to the program.  So argv[0] points to the first parameter, which is the program name/command used to run the program. argv[1] is the 1st parameter passed to the program etc etc.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:Andy36
ID: 6426951
I am not understanding templates. I thought using templates you had to write a implementation file and a headr file as well but this stack for infix to post fix works but I do not have any Implementation file or header.

This code example works for infix to post fix and I guess the implementation file is a generic file already written in the C++ STL. Are my thoughts correct?
//  Data Structures with C++ by John R. Hubbard
//  Copyright McGraw-Hill, 2000
//  Example 5.3 page 95
//  Using a stack to convert infix expressions to postfix

#include <iostream>
#include <sstream>  // defines the istringstream class
#include <stack>    // defines the stack<T> class template
using namespace std;

int main()
{ stack<char> op;    // stack for operators
  string s;
  cout << "Enter an infix expression: ";
  getline(cin,s);
  istringstream in(s);  // convert input to stringstream
  char c;
  while (in >> c)
  {
    if (c=='+' || c=='-' || c=='*' || c=='/') op.push(c);
    else if (c==')')
    { cout << op.top() << " ";
      op.pop();
    }
    else if (c>='0' && c<= '9')
    { in.putback(c);
      int n;
      in >> n;
      cout << n << " ";
    }
  }
  cout << op.top() << endl;
}
0
 
LVL 22

Expert Comment

by:nietod
ID: 6427056
>> I thought using templates you had to
>> write a implementation file and
>> a headr file as well
You don't have to have either.  You can write a template class right in your main .cpp file like

template <class T>
class SomeClass
{
}

int main()
{
   SomeClass<char> X;
   return 0;
};

You only need a .h file when you want to share code between multiple source code files (translation units).  you only need to place code for a class in a .cpp that is not you main .cpp file if you want to try to organize your code.  

Now both of these things are good things to do.  its good to organize your code into seperate .cpp files and its good to use .h files to allow classes and other elements that your write to be shared and reused.  But you don't have to do either.


>> I guess the implementation file is a generic file
>> already written in the C++ STL

The stack class you posted in your original question is defnitely ot the STL stack class.  For example, the pop() functin works differently.  The STL pop does not return a value, but the one that appears in your question does return a value.
0
 

Author Comment

by:Andy36
ID: 6427411
My real task is to make a stack linked list that changes infix to postfix. I am supose to use a template for the stack and write the linked list code. I would then have to have a header and implementation file for the LL. What I do not understand is what the linked   list is going to be doing in the program. The stack changes infix to postfix. Is a template just a generic header and implementation files in the STL?
0
 
LVL 22

Expert Comment

by:nietod
ID: 6428105
Then the first thing you need to do is to write the stack.  That is the tool that you will use to change the expression.  If you don't yet have that tool, you can't try to change the expression.

>> What I do not understand is what the linked  
>> list is going to be doing in the program.
the program never (explicitly) uses the linked list.  There will be no evidence at all of the existance of the linked list when you look at the main program.

The stack will use the linked list.  when something is pushed onto the stack it is stored in the linked list.  When something is poped from the stack, it is removed from the linked list.   Only the stack class "knows" about the linked list.

>> The stack changes infix to postfix.
No.  That is what the program that uses the stack does.  The stack just stores data at the program's request.  

Write the atack first.  You need to declare at least one data member in the stack so that it can record the data in the linked list.  Then you need to write a push and pop function.  the posh function needs to place 1 item on the list and the pop needs to remove one item.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
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.

705 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

18 Experts available now in Live!

Get 1:1 Help Now