Hello. I am trying to search for an element in a binary search tree using a class object but I cant get my code to work right. I have a class called Stock which has three private members: compName, compSymbol, compPrice. Here I am supposed to ask the user for a Stock symbol, search for that stock in the tree, and then display the name of that stock. Every time I try to search for a Stock symbol it just outputs 'Not found' even if I know it is in there. I don't understand why I can't get it to work.
Here is what I have in main. This is the code I am having promblems with:
Code:
int main()
{
BinarySearchTree<Stock> tree;
Stock company[23];
string name,
symbol;
const int DISPLAY_NAME = 1,
DISPLAY_PRICE = 2,
INSERT = 3,
DISPLAY_ALL = 4,
QUIT = 5;
//this is a menu driven program, i only posted the part of the program i am having issues with
if (choice == DISPLAY_PRICE)
{
//Stock tempSymbol;
cout << "Enter the stock's symbol to display the price: ";
cin >> symbol;
//symbol = tempSymbol.getSymbol();
//tempSymbol.setSymbol(symbol);
Stock* ptr = tree.search(symbol);
if (ptr == nullptr)
cout << "Not found.\n";
else
cout << ptr->getPrice();
cout << endl;
}
}
I tried using Stock's member functions get and set (accessor and mutator member functions) for both the symbol and the price but I still can't get it to work. I left a little bit of what I tried in the code above and commented it out.
Here are some of the functions in the Stock class. The rest of the code here is just for clarification :
Code:
class Stock
{
private:
string compName;
string compSymbol;
double compPrice;
public:
string getName() const;
void setName(string name);
string getSymbol() const;
void setSymbol(string symbol);
double getPrice() const;
void setPrice(double price);
And then the code in the BinarySearchTree is this:
Code:
template <typename T>
T* BinarySearchTree<T>::search(const T& item) const
{
T* result;
result = search(root, item);
return result;
}
template <typename T>
T* BinarySearchTree<T>::search(Node<T>*r, const T& item) const
{
T* result;
if (r == nullptr)
result = nullptr;
else if (r->info > item)
result = search(r->left, item);
else if (r->info < item)
result = search(r->right, item);
else
result = new T(r->info);
return result;
}
I know there is nothing wrong with my search code because my teacher helped the class with it. I just put it here for clarification.