【问题标题】:std::set with custom comparator带有自定义比较器的 std::set
【发布时间】:2018-10-30 18:44:26
【问题描述】:

我正在尝试在一组中按 wordCount 降序排列 wordItems。

我从事数据结构方面的工作,我们的教授向我们提出了在以前的作业中使用 STL 容器的挑战。这里使用 std::set 的原因是因为我的教授想向我们展示如何在实践中使用 STL BST。

我似乎无法弄清楚 std::set 及其所有功能...

这是我认为与我的 wordItem 结构相关的代码:

// header file (HashTable.hpp)
struct wordItem
{
    std::string word;
    int count;
    wordItem* next;
};

struct comp 
{
    // I have also tried bool operator<()(wordItem const &lhs, wordItem const &rhs)     
    bool operator()(wordItem const &lhs, wordItem const &rhs) const {
        if (lhs.count == rhs.count) {
            return lhs.word > rhs.word;
        }
        return lhs.count > rhs.count;
    }
};

然后这是我的函数,它实际上会使用这个集合:

// implementation file (HashTable.cpp)
#include "HashTable.hpp"
void HashTable::printTopN(int n) {
    set<wordItem,comp> s;

    for (int i = 0; i < hashTableSize; i++) {
        if (hashTable[i] != nullptr) {
            wordItem *temp = hashTable[i];
            s.insert(*temp);
            while (temp->next != nullptr) {
                temp = temp->next;
                s.insert(*temp);
            }
        }
    }
}

但是,我收到一条错误消息,指出我正在使用未声明的标识符。 comps 都导致了这个...... 这是确切的错误消息:

HashTable2.cpp:129:16: error: use of undeclared identifier 'comp' 
set<wordItem,comp> s;
             ^
HashTable2.cpp:134:7: error: use of undeclared identifier 's'
s.insert(*temp);
^
HashTable2.cpp:137:9: error: use of undeclared identifier 's'
s.insert(*temp); 
^

该集合应该首先包含 wordItem 和最大的 wordCount,如果两个单词的计数相同,则决胜局应该是字典顺序。

我觉得问题可能来自我可能没有正确比较这些 wordItem 的事实

最后,我深表歉意,因为我认为将我自己的自定义数据结构与 STL 结构混合起来非常麻烦,但我们将不胜感激任何帮助

【问题讨论】:

  • 请提取minimal reproducible example。这也应该可以帮助您自己排除一些常见错误。另外,逐字引用完整的错误,不要转述!

标签: c++ data-structures set


【解决方案1】:

当您使用自定义比较器时,std::map 将其用作

comp_object(a, b)

struct comp {
    bool operator<(wordItem const &lhs, wordItem const &rhs) const {
        if (lhs.count == rhs.count) {
            return lhs.word > rhs.word;
        }
        return lhs.count > rhs.count;
    }
};

你定义了一个operator &lt;,而不是operator (),所以它不会工作。改成

struct comp {
    bool operator()(wordItem const &lhs, wordItem const &rhs) const {
        if (lhs.count == rhs.count) {
            return lhs.word > rhs.word;
        }
        return lhs.count > rhs.count;
    }
};

它会起作用的。这称为函子,您可以在此处阅读更多信息:What are C++ functors and their uses?

【讨论】:

  • 感谢您的快速回复@NathanOliver!我肯定会阅读函子及其用途!但是,我想我不知道在这种情况下我的问题来自哪里(因为我正在使用 std::set):我将 bool operator&lt;() 更改为 bool operator()() 并且未声明的标识符错误仍然存​​在......
  • @pickypoo1987: 是在HashTable::printTopN可以找到的地方定义了comp,也就是在某个头文件#include-ed在源文件里面HashTable::printTopN是定义?你确定你保存了这两个文件?鉴于您实际上并未提供minimal reproducible example,因此很难确定任何消息。
  • @ShadowRanger 我在这方面特别纠结于完整和可验证的方面:(但是,我将更改上面的代码以尝试澄清!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-07
  • 2022-01-28
  • 2021-10-23
相关资源
最近更新 更多