使用来自另一个类的函数或此类中的函数中的结构

Use function from another class or struct in a function within this class

本文关键字:函数 结构 另一个      更新时间:2023-10-16

我正在创建一个哈希表,需要使用不同的哈希函数测试这个链式哈希表。我有哈希结构,例如

struct Hasher {
    virtual int hash(std::string s, int N) = 0;
};
struct SumHasher : Hasher {
    int hash(std::string s, int N){
        int result = 0;
        for (int i=0; i<s.size(); ++i)
            result += s[i];
        return int (std::abs((int)result)) % N;
    }
};
struct ProdHasher : Hasher {
    int hash(std::string s, int N) {
        int result = 1;
        for (int i=0; i<s.size(); ++i)
        result *= s[i];
    return int (std::abs((int)result)) % N;
    }
};
struct ShiftHasher : Hasher {
    int hash(std::string s, int N){
    const int shift = 6; unsigned z = 0;
    const int mask = ~z >> (32-shift); // lower 6 bits on
    int result = 0;
    for (int i = 0; i < s.length(); i++)
        result = (result << shift) | (s[i] & mask);
    return int (std::abs((int)result)) % N;
    }
};

现在,我如何通过创建结构哈希类型然后将该对象传递给构造函数来在 Hashtable 类中使用此函数

class ChainedHashTable
{
    ListNode **T; // array of linked lists
    int capacity;
public:
    Hasher *myhash;
    int info;
    ChainedHashTable(int numberOfChains, Hasher *myHasher){
        myhash = hasher;
        capacity = numberOfChains;
       T = new ListNode* [capacity];
       for (int i=0; i<capacity; ++i)
           T[i] = NULL;
     }
.......
void ChainedHashTable::insert(std::string key, int info){
    int h = myhash::hash(key, capacity);
    T[h] = ListNode::make(key, info, T[h]);
}

你应该使用:

myhash->hash(key, capacity)