c++ - 检查数组中的字符串是否为空时出错

标签 c++ string pointers struct hashtable

<分区>

我正在设置一个哈希表,我已经计算出 key ,并想确定数组中的那个位置是否已经包含某些内容。我想我应该检查它是否为 null 以查看该空间是否为空或是否已被删除。 del.compare是检查first name字符串是否被"DEL"替换,我就是这样标记已经删除准备重写的元素.

我收到一个错误:

错误:'operator!=' in '(((Student*)this)->Student::studentList + ((unsigned int)(((unsigned int)((Student*)this) 不匹配)->Student::key) * 20u)))->Student::studentEntry::FIRST != 0'

对于这一行:

if(studentList[key].FIRST != NULL || del.compare(studentList[key].FIRST) != 0)

在这种情况下使用 != 有什么问题?

编辑del.compare:

我只是使用字符串库比较,在这种情况下 del 在函数中初始化:

string del("DEL");

studentList[key].FIRST对应一个指向字符串结构的指针,初始化为10studentList[0].FIRST 应该是 10 数组中第一个条目的名字,它应该是空的。

这是我在构造函数中声明它的方式:

studentList = new studentEntry[10];

编辑FIRST:

FIRSTstudentEntry 结构内的 Students 类中声明。那部分看起来像:

class Student
{
    private:    
        struct studentEntry
        {
            string FIRST; 
        };
        studentEntry *studentList;
        int key;
        int index;

    public:
        void add(string &firstname);
        Student();
};

这是 Student 类的构造函数,它也可能是相关的:

Student::Student()
{
    studentList = new studentEntry[10];
    key = 0;
    index = 0;  
}

编辑添加:

下面是 add 函数,其中进行了导致错误的比较:

void Student::add(string &firstname)
{       
    string del("DEL");

    //find key to know which bucket to use
    key = index % 10;

    //check if spot in studentList is empty or has been removed
    if(studentList[key].FIRST != NULL || del.compare(studentList[key].FIRST) != 0)
    {
        //do stuff
    }
}

最佳答案

编译器说 del.compare 的结果与 0 不可比较

你还没有显示任何关于del.compare的信息,所以不能说更多

目前缺少 FIRST 的声明……


一段时间后 - FIRST 现在显示为 string,可能是 std::string

您不能将 std::string 与 0 或 nullptr 进行比较。

但是你可以比较它的 length() 和 0,例如。

关于c++ - 检查数组中的字符串是否为空时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15047536/

相关文章:

c++ - 这是 "*ptr++ = *ptr + a"未定义的行为吗?

c++ - 如何在 C++ 中解析基于文本的表格

c - void * 函数的输入在函数结束时丢失地址

c++ - C++ 中使用 char* 的指针算术

c++ - 将动态创建的对象分配给作为类的私有(private)成员的指针有什么问题吗?

c++ - 涉及模板参数解决方法的模板参数

c++ - 出色的 C++ 项目 36

python - 用 ldexp 反转 frexp

c++ - 无法弄清楚 C++ 中的指针!需要有关基本字符串和指针的信息

typescript - 从 Typescript 类型中提取信息