尝试打印对象列表的矢量时出错

Errors when trying to print out vector of list of objects?

本文关键字:出错 列表 打印 对象      更新时间:2023-10-16

所以我试图用下面的代码打印出哈希表中对象列表的向量,但我一直收到这些错误,我不知道为什么。。。

SeparateChaining.h: In member function 'void HashTable<HashedObj>::print()':
SeparateChaining.h:165:13: error: need 'typename' before 'std::list<HashedObj>::iterator' because 'std::list<HashedObj>' is a dependent scope
SeparateChaining.h:165:39: error: expected ';' before 'li'
SeparateChaining.h:166:17: error: 'li' was not declared in this scope
SeparateChaining.h: In instantiation of 'void HashTable<HashedObj>::print() [with HashedObj = Symbol]':
Driver.cpp:72:21:   required from here
SeparateChaining.h:165:13: error: dependent-name 'std::list<HashedObj>::iterator' is parsed as a non-type, but instantiation yields a type
SeparateChaining.h:165:13: note: say 'typename std::list<HashedObj>::iterator' if a type is meant

以下是我的类中具有打印功能的片段:

class HashTable
{
    /// ....

        void print()
        {
            for(int i = 0; i < theLists.size(); ++i)
            {
                list<HashedObj>::iterator li;
                for(li = theLists[i].begin(); li != theLists[i].end(); ++li)
                    cout << "PLEASE WORK" << endl;
            }
    /*
            for(auto iterator = oldLists.begin(); iterator!=oldLists.end(); ++iterator) 
                for(auto itr = theLists.begin(); itr!=theLists.end(); ++itr)
                    cout << *itr << endl;
    */
        }
      private: 
         vector<list<HashedObj>> theLists;   // The array of Lists
};

下面是我如何重载ostream运算符<lt;(在符号类中(:

friend ostream & operator <<(ostream & outstream, Symbol & symbol) //overloaded to print out the the HashTable
{
    int num = symbol.type;
    string name = symbol.data;
    outstream << name << " : " << num << "n";
    return outstream;
}

如果你仔细阅读错误,它会说这一行:

list<HashedObj>::iterator li;

应读作:

typename list<HashedObj>::iterator li;

基本上,您需要告诉编译器您正在处理一个类型。有关正在发生的事情的更多详细信息,请参阅此问题或此问题。

您可能还有其他错误,但需要先解决这些错误。

SeparateChaining.h:165:13: error: need 'typename' before 'std::list<HashedObj>::iterator' because 'std::list<HashedObj>' is a dependent scope

编译器无法确定list<HashedObj>是静态字段还是类型,因此它假定list<HashedObj>是导致这些语法错误的字段。您必须在声明前面放置一个typename来说服编译器。它应该看起来像:

typename list<HashedObj>::iterator li;

看看这个类似的帖子