如何使用带有向量的哈希表创建构造函数单独链接

问题描述

我正在尝试为用于单独链接的向量哈希表创建构造函数。我不断收到一条错误消息:

错误:'table' 之前的预期主表达式

#include <iostream>
#include <vector>
#include <list>
#include <stdexcept>

// Custom project includes
#include "Hash.h"

// Namespaces to include
using std::vector;
using std::list;
using std::pair;

//
// Separate chaining based hash table - inherits from Hash
//
template<typename K,typename V>
class ChainingHash : public Hash<K,V> {
private:
    vector<list<V>> table;          // Vector of Linked lists

public:
    ChainingHash(int n = 11) {

        table = vector<list<K,V>> table(n);

    }

解决方法

这行没有意义。您正在尝试将赋值表达式与变量定义语句结合起来。不仅如此,您还拥有 list<K,V>,当您的存储表需要 list<V>...

时,这毫无意义
table = vector<list<K,V>> table(n);  // <-- completely broken syntax

要在构造函数中初始化您的表,您需要做的就是使用初始化列表:

ChainingHash(int n = 11)
    : table(n)
{
}

使用上面的构造函数定义,table 成员将被初始化为 n 空列表,这似乎是您尝试执行的操作。