std::设置自定义比较器

std::set with custom comparator

本文关键字:比较器 自定义 设置 std      更新时间:2023-10-16

我正试图在集合中按wordCount降序排列wordItems。

我是研究数据结构的,我们的教授给了我们在以前的作业中使用STL容器的挑战。这里之所以使用std::集,是因为我的教授想向我们展示如何在实践中使用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结构混合在一起非常混乱,但如果有任何帮助,将不胜感激

使用自定义比较器时,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 <,而不是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;
}
};

它会起作用的。这被称为函子,你可以在这里阅读更多关于它的信息:C++函子是什么及其用途?