3

I am making my own dictionary using templates (no I can't and I won't use anything from STL).

I want to have a very simple search function, but I have a small problem.

template <typename TElement>
void Dictionary<TElement>::search(TElement ADT, int key) {  // Abstract Data Type
    inf flag = 0;
    index =  int (key % max);
    temp[index] = root[index]; // root of the hash
    while (temp[index]->next != NULL) {
        if(temp[index]->data->key_actual_name == key) { @things happen }
    }
}

What I want to understand: how to use template so that I can have temp[index]->data-><template call> if that makes any sense

I want to call the dictionary by using: Class_type == TElement and "key" is always an int but it can be different things. It might be an ID or phone number. Problem is I need to use the actual name of the key (if(temp[index]->data->ID (or phone or what ever) == key) { @things happen }), I imagine I could use templates here but I don't know how.

also maybe relevant:

template <typename TElement>
typedef struct list{
    TElement data;
    struct list *next;
}node_type;
node_type *ptr[max], *root[max], *temp[max]; 

Also, if I do use a template for key_actual_name, how would the implementation work AND how would I call that function ?

4

2 回答 2

5

你可以从标准库函数中获得一些灵感,比如find_if有一个额外的参数进行比较。

template <class InputIterator, class Predicate>
InputIterator find_if ( InputIterator first, InputIterator last, Predicate pred );

然后,您可以传递一个参数,告诉search函数如何找到您要查找的密钥。也许用==with代替

if(pred(temp[index]->data, key)) { @things happen }

并传递不同pred的函数以将密钥与适当的成员进行比较。

于 2012-05-29T14:45:07.743 回答
1

如果我理解正确:

temp[index]->data->key_actual_name

解析为 TElement 的数据成员,它是一个 int,并且您希望它是一个模板。如果是这种情况,您可以这样做:

template <template <class> class TElement, typename TKey>
struct node_type
{
    TElement<TKey> data;
    node_type *next;
};

template <template <class> class TElement, typename TKey>
class Dictionary
{
    typedef node_type<TElement, TKey> node_t;
    node_t _root;

    void search(node_t& node, const TKey& key)
    {
        TKey& thekey = node.data.key_actual_name;
        // Do some algorithm
    }
public:
    void search(const TKey& key)
    {
        search(_root, key);
    }
};

template <class T>
struct Element
{
    T key_actual_name;
};

int main(int argc, char ** argv)
{
    Dictionary<Element, int> dic1;
    dic1.search(1);

    Dictionary<Element, char> dic2;
    dic2.search('a');

    return 0;
}

如您所见,Element 有一个模板参数,因此您可以将 key_actual_name 的类型更改为适合您的情况,但让搜索函数以通用方式访问它(假设它具有 operator== 重载)。

于 2012-05-29T15:00:45.147 回答