gpt4 book ai didi

c++ - 具有相同模板的不同参数

转载 作者:行者123 更新时间:2023-11-28 06:33:05 26 4
gpt4 key购买 nike

我正在尝试创建一个使用模板的 HashMap 。该模板将采用散列函数(以 hash ( int key, int size ) 的形式)和一个探测函数(在探测和探测的情况下以 probe ( int i ) 的形式出现 ( int key, int size )在双哈希的情况下。我希望你明白我在说什么。这是我的主要内容:

#include "generic_map.h"

inline int hash( int key, std::size_t M ) { return key % M; }
inline int hash2( int key, std::size_t M ) { return key % (M-1) + 1; }
inline int linear_probe( int i ) { return i; }
inline int quadratic_probe( int i ) { return i*i; }


int main() {

generic_map<int, char, int(*)(int,std::size_t), hash, int(*)(int), quadratic_probe, false> map1( 20);

generic_map<int, char, int(*)(int,std::size_t), hash, int(*)(int, std::size_t), hash2, true> map2( 20);

}

如您所见,我传入了两种不同的指针函数类型作为探测函数。在双重散列的情况下,“Hash2”将作为探测函数传入。这是我的头文件中的一个片段(即我的类声明、节点声明和插入方法:

template <class KEY, class VALUE, class HASH_FUNC, HASH_FUNC hash, class PROBE_FUNC, PROBE_FUNC probe, bool double_hash>
//Hashmap Class
class generic_map {

private:

//Node Class
struct hashNode {

KEY key; //Stores the key of node
VALUE value; //Stores the value that associates to key

hashNode(KEY key, VALUE &value) : key(key), value (value) {} //hashNode constructor

};

public:

//Creates a new backing array with user inserted capacity
generic_map( int capacity ) {

M = capacity;
map = new hashNode * [capacity];

for(int i = 0; i < M; ++i) {
map[i] = NULL;
}
}

//Deletes the hashNodes in the list and the map
~generic_map() {
clear();
}

//If index that key hashes to is empty, insert. Else, replace value at hashed index.
int insert( KEY key, VALUE value ) {

int f = hash( key, M );
int p = 0;
int h = f;

while( map[h] != NULL ) {

if( p == M )
return -1 * p;

if( map[h]->key == key ) {
map[h]->value = value;
return p;
}
else {
++p;
if(double_hash) {
h = f + (p * probe(key, M)) % M;
}
else {
h = f + (probe( p )) % M; //This is throwing an error and will not compile,
} //saying, "too few arguments to function call.
}
}

我的插入方法中“double_hash_ 条件”的“其他”部分标记了一个错误,因为我当然调用了同一个探针,具有两个不同参数编号的模板函数。我不是在问为什么它会抛出错误,因为我已经知道原因了。我正在寻求解决方案或解决方法。谢谢。

最佳答案

以下是我能想到的一些解决方案:

  1. 一个快速而肮脏的修复是为单参数探测函数声明一个虚拟的默认第二个参数,它不会被使用,比如

    inline int linear_probe( int i, int dummy = 0 ) { return i; }

    现在 linear_probe 实际上有 2 个参数,但默认情况下会初始化一个,因此您可以使用 2 参数函数指针指向它。但是这个解决方案不是最优雅的,可能你应该考虑改变你的设计。为什么不制作 2 个单独的类,一个用于简单散列,一个用于 double ?或者使双重哈希继承自简单哈希。

  2. 使用模板特化

    你需要特化类generic_map对于 truefalse .保留您的通用定义,但只专门化 2 个版本,如 template<typename types (omit bool here as we specialize)> generic_map<types, true> .看看这里例如:http://cprogramming.com/tutorial/template_specialization.html

关于c++ - 具有相同模板的不同参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27203712/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com