C++ - 带有函数指针的哈希表
C++ - Hash table with function pointers
这是我在这个网站上的第一篇文章。我正在一个项目中,我用C++编写了一个哈希表。我对函数指针有问题。
我有一个包含一些学生的哈希表(由学生的编号标识)。我必须使用函数指针在参数中传递哈希。
我的代码在:
//file main.cpp
Table t1;
unsigned int(Table::* ptrHash)(unsigned int);
ptrHash = &Table::hash;
t1.insertStudent(11507461, 20, ptrHash);
// file Table.cpp
void Table::insertStudent(unsigned int numberStudent, unsigned int (*f)(unsigned int)) {...}
unsigned int Table::hash(unsigned int cleEtu) {...}
//file Table.h
void insertStudent(unsigned int numberStudent, unsigned int (*f)(unsigned int));
unsigned int hash(unsigned int numberStudent);
我的提示给了我这个错误:
no matching function for call to 'Table::insertStudent(int, unsigned int (Table::*&)(unsigned int))' t1.insererEtu(11507461, 20, ptrHachage);
note:no known conversion for argument 3 from ‘unsigned int (Table::*)(unsigned int)’ to ‘unsigned int (*)(unsigned int)’
我知道它不一样,但我不知道如何解决它。我尝试了很多方法,但没有一种有效。
如果有人能帮助我,它会救我!
问题的原因是指向普通函数的指针和指向成员函数的指针之间存在差异。该函数insertStudent
采用指向普通函数的指针,但您可以使用指向 Table
类中的成员函数的指针调用它。
就个人而言,在这种情况下我根本不会使用函数指针,我会让 insertStudent
在哈希函数上参数化。这将允许哈希函数是具有接受int
并返回int
的函数调用运算符的任何对象。
如果我的老师强迫我使用函数指针,我会使哈希函数成为Table
类的静态成员函数,以保持它的接近。静态成员函数和非静态成员函数之间存在根本区别。静态成员函数不是在特定对象上调用的,因此与普通函数的关系更接近。
相关文章:
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 用C++将哈希表写入文件并从文件中恢复
- C++中的并发哈希表
- 在具有开放寻址的哈希表中插入节点 [优化逻辑]
- 与C++哈希表的基础知识混淆
- 调整大小和复制哈希表数组中的元素
- 带链接的基本哈希表
- C++哈希表中,两个相同的实现,但一个给出错误
- 如果索引不是整数,我们如何在 C++ 中插入哈希表
- 查找项目在哈希表中的位置
- 为什么C++ STL 哈希表 (unordered_map) 不接受向量作为键
- C++哈希表 - 如何解决自定义数据类型作为键的unordered_map冲突?
- 使用哈希表设置实现
- 同时写入和读取哈希表
- 创建用于存储某些指针值的哈希表
- 跟进哈希表 C++,this->next = NULL 指针
- C++ - 带有函数指针的哈希表
- 如何减少哈希表槽中的指针/地址宽度
- 指向哈希表中指针的指针