【问题标题】:Can I compare vector objects to NULL?我可以将矢量对象与 NULL 进行比较吗?
【发布时间】:2017-05-10 17:43:38
【问题描述】:

我来自 Python/Java 领域,现在我正在尝试用 C++ 制作自己的哈希图。

当我尝试检查以将哈希表中的位置位置与 NULL 进行比较时(第 6 行和第 11 行),我收到错误:

invalid operands to binary expression ('value_type' (aka 'HashEntry') and 'long')"

我希望有人能引导我了解我做错了什么以及如何解决它。

void CustomHash::insert(HashEntry entry) {
    int k = entry.getKey();
    int i = 0;
    int hashVal = hash_One(k);
    int temp = hashVal;
    while (i < size && hashArray[temp] != NULL) {
        i++;
        temp = (hashVal + i*hash_Two(k)) % size;
    }

    if (hashArray[temp] == NULL) {
        hashArray[temp] = entry;
    }
    else {
        cout << "Failure" << endl;
    }
}

编辑 1:hashArray 声明

CustomHash::CustomHash(int m) {
    this->size = m;
    this->hashArray = vector<HashEntry>();
}

【问题讨论】:

  • 编译器告诉你这是一个错误。如果您出示hasArray 的声明,也许有人可以提供解决方案。
  • hashArray.count(temp)
  • @Justin André 正在编写自己的哈希图作为练习。可以合理地假设 hashArray 属于该类型而不是标准哈希映射。因此,您不能假设它具有 count 方法。
  • 不要在现代 C++ 中使用 NULL - 我们现在有 nullptr
  • @RSahu hashArray 是一个向量 对象

标签: c++ vector null comparison


【解决方案1】:

给定,

hashArray 是一个vector&lt;HashEntry&gt; 对象

hashArray[temp] 的计算结果为 HashEntry。您无法将 HashEntryNULL 进行比较。

使用不同的策略来检查hasArray 是否有任何项的键等于temp。我建议使用std::count_if

while (i < size && std::count_if(hashArray.begin(), hashArray.end(),
                                 [=temp](HashEntry const& e)
                                 { return (temp == e.getKey());}) > 0 )
{
    i++;
    temp = (hashVal + i*hash_Two(k)) % size;
}

正如@cdhowie 所建议的,更好的解决方案是使用std::any_of

while (i < size && std::any_of(hashArray.begin(), hashArray.end(),
                               [=temp](HashEntry const& e)
                               { return (temp == e.getKey());}) )
{
    i++;
    temp = (hashVal + i*hash_Two(k)) % size;
}

【讨论】:

  • 我会建议 std::any_of 而不是 std::count_if,因为条件是 &gt; 0 -- 如果我们找到匹配项,我们可以提前停止。
  • @cdhowie,谢谢。这是一个更好的解决方案。
猜你喜欢
  • 2022-09-30
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-08
  • 1970-01-01
  • 2010-12-30
相关资源
最近更新 更多