0

I'm trying to make my own BST. I've made class Tree, which uses Templates.

template <class T>
class Tree {
public:
    Tree(void);
    void insert (T key);
private:
    Node<T>* root;
};

In method main i have something like that:

Tree<int>* d = new Tree<int>();
int key;
cin >> key;
d->insert(klucz);

I recived an error:

unresolved external symbol "public: void __thiscall Tree[int]::insert(int)" (?insert@?$Tree@H@@QAEXH@Z) referenced in function _main

I wonder, how can I read data from user without precising type of "key" field.

David G
  • 94,763
  • 41
  • 167
  • 253
siwy
  • 13
  • 3

1 Answers1

2

You do not have Tree::insert defined anywhere, yet you declare it. It practically doesn't exist so you need to add the function:

//just code to make this example, and be able to compile it
template <class T> class Node
{
private:
    std::vector<T> keys;
public:
    Node()
    {

    }
    size_t Add(T key)
    {
        keys.push_back(key);
        return keys.size() - 1;
    }
};

//tree.h
template <class T>
class Tree {
public:
    Tree(void);
    void insert (T key);
private:
    Node<T>* root;
};

//tree.cpp
template <class T> Tree<T>::Tree (void)
{
    //construction code here
    //example:
    root = new Node<T>;
}

template <class T> void Tree<T>::insert (T key)
{
    //insert code here
    //example:
    root->Add(key);
}

//main.cpp
int main()
{
    Tree<int>* d = new Tree<int>();
    int key;
    std::cin >> key;
    d->insert(key);
    return 0;
}

if you want to read any data and convert between string, integers, doubles etc then I suggest you to look at boost::any or boost::lexical_cast, after a few modifications you can do something like this:

template <class T> class Node
{
private:

public:
    std::vector<T> keys;
    Node()
    {

    }
    size_t Add(T key)
    {
        keys.push_back(key);
        return keys.size() - 1;
    }
};

template <class T>
class Tree {
public:
    Tree(void);
    void insert (T key);
    T& get(size_t index);
private:
    Node<T>* root;
};

template <class T> Tree<T>::Tree (void)
{
    //construction code here
    //example:
    root = new Node<T>();
}

template <class T> void Tree<T>::insert (T key)
{
    //insert code here
    //example:
    root->Add(key);
}

template <class T> T& Tree<T>::get (size_t index)
{
    //get code here
    //example:
    return root->keys[index];
}

#include <boost/lexical_cast.hpp>
int main()
{
    Tree<std::string>* d = new Tree<std::string>;
    std::string key;
    std::cin >> key;
    d->insert(key);
    std::cout << "Your input:\n";
    std::cout << "\tString: " << boost::lexical_cast<std::string>(d->get(0)).c_str() << "\n";
    std::cout << "\tFloat: " << boost::lexical_cast<float>(d->get(0)) << "\n";
    std::cout << "\tDouble: " << boost::lexical_cast<double>(d->get(0)) << "\n";
    std::cout << "\tInt: " << boost::lexical_cast<int>(d->get(0)) << "\n";
    return 0;
}

output:

enter image description here