【发布时间】: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);
}
}
}
}
但是,我收到一条错误消息,指出我正在使用未声明的标识符。 comp 和 s 都导致了这个......
这是确切的错误消息:
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