Having problems with TURBO c++

Nov 22, 2009 at 12:16pm
I ran the following program in Turbo C++ and got some errors related to the usage of the new operator. However, when i ran it in UNIX, or the g++ version of UNIX, it ran alright. The headache is that in my archaic college they still use this obsolete version of C++.
Please help.

The question is regarding the genericity of the class binary search tree. We have to make a function that searches for an element in it.

Here's the code.

#include<iostream.h>
#include<conio.h>


template<class T>
class bst
{
T element;
bst *left,*right;
public:
bst* makebst(T x,bst* t)
{
if(t==NULL)
{
t =new(bst);//THIS LINE LEAVES ME RUNNING FOR ASPIRIN
t->element = x;
t->left = t->right = NULL;
}
else
{
if(x < t->element)
t->left = makebst(x, t->left);
else if(x > t->element)
t->right = makebst(x, t->right);
}
return t;
}

int search(T x, bst* t)
{
if(t==NULL)
return 0;
if(x<t->element)
return search(x,t->left);
if(x>t->element)
return search(x,t->right);
return 1;
}



};

bst<float>*temp,*root,*l,*start;


int main()
{
clrscr();
int a[20],ch,n,i,p,s;
root=NULL;
cout<<"\nEnter the number of elements ";
cin>>n;
cout<<"\nEnter the array\n";
for(i=0;i<n;i++)
{
cout<<"\n Enter element "<<i+1<<":";
cin>>s;
root=root->makebst(s,root);
}
cout<<"\nEnter the element to be searched ";
cin>>p;
ch = temp->search(p, root);
if (ch!=0)
cout<<"\n Element found";
else
cout<<"\n Element not found";
getch();
return 0;

}


Thanks in advance.

Nov 22, 2009 at 12:29pm
Please use code tags.

You can't have a type that's just bst or bst*. bst is a template class, and therefore in order to have any types you need to instantiate it with a template parameter.

Try the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
template<class T>
  class bst
  {
  T element;
  bst<T> *left,*right;  // note:  bst<T>, not bst

public:
  bst<T>* makebst(T x,bst<T>* t)  // again note the <T>s
  {
    if(t==NULL)
    {
      t =new bst<T>;  //Again <T>.  I also got rid of the parenthesis because they look weird to me
      t->element = x;
      t->left = t->right = NULL;
...


Pretty much everywhere you have just bst you should replace it with bst<T> except for the class bst line at the top.
Nov 23, 2009 at 6:57am
thanks a lot.
It was really helpful.
Nov 23, 2009 at 6:50pm
Man, just dont use Turbo C, it's totally out-standard.
Topic archived. No new replies allowed.