列表的矢量

A vector of lists

本文关键字:列表      更新时间:2023-10-16

我第一次尝试实现一个链式哈希表。我想创建一个列表向量。所以我声明了一个向量列表为私有。

class HashTable{
public:
    HashTable( int ) ;
    void add( int k ) ;
    int remove( int k ) ;
    int find( int k ) ;
private:
    vector< list > t ;
    int n ; 
    int hash( int ) ; 
};

它显示以下错误:

\"template class std::vector"的模板参数列表中的参数1处的HashTable.cpp[Error]类型/值不匹配

基本上我的问题是列出一个类型,所以如果我们可以声明int的向量,为什么不能声明List的向量?

您忘记了list的模板参数。它不能只是list,它必须是类似std::list<int>的列表(其中int可以是任何其他类型,但由于所有其他成员函数都使用int,我在示例中使用了int)

下面的代码说明了这个问题:

#include <vector>
#include <list>
int main(int argc, char* argv[])
{
    std::vector< std::list<int> > v; // this compiles 
    std::vector<std::list> v2;  // and this doesn't
    return 0;
}

如下所示,所有编译错误都来自第7行(列表中缺少模板参数的行)。这是在ideone 上编译的

prog.cpp: In function ‘int main(int, char**)’:
prog.cpp:7:26: error: type/value mismatch at argument 1 in template parameter list for ‘template<class _Tp, class _Alloc> class std::vector’
prog.cpp:7:26: error:   expected a type, got ‘list’
prog.cpp:7:26: error: template argument 2 is invalid
prog.cpp:7:30: error: invalid type in declaration before ‘;’ token
prog.cpp:7:28: warning: unused variable ‘v2’ [-Wunused-variable]

您必须指定列表应包含的元素类型。你不能只说"一个列表",你必须说"某种类型的t的列表"。列表模板采用一个参数,就像vector一样,所以您必须说一些类似std::vector<std::list<char*> >的内容。如果您不使用C++11,请注意在第一个>之后留一个空格,否则它将无法工作,因为它被解析为>>运算符。