std::设置自定义比较器
std::set with custom comparator
我正试图在集合中按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);
}
}
}
}
然而,我收到一条错误消息,说我正在使用未声明的标识符。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结构混合在一起非常混乱,但如果有任何帮助,将不胜感激
使用自定义比较器时,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++函子是什么及其用途?
相关文章:
- std::设置自定义比较器
- 带自定义比较器的最小优先级队列
- 优先级队列自定义比较器
- 什么是自定义比较器以及如何在 C++ 的排序函数中使用它?
- 没有默认构造函数作为模板参数的自定义比较器
- set_intersection使用自定义设置比较器
- 比较迭代器会使程序崩溃,而不会在自定义气泡排序实现中出现错误
- 使用迭代器的自定义比较器函数
- Cython中带有自定义比较器的优先级队列
- gtest 期望无序元素与自定义比较器/匹配器一起使用
- 定义具有非标准签名的自定义映射比较器
- 为什么在类或结构中传递自定义比较器函数?
- 在priority_queue中使用默认容器但自定义比较器
- 是否有任何统一的方法可以在 c++ 中创建自定义比较器?
- C++ priority_queue与自定义比较器并删除任何项目
- 如何在 C++11 中将 std::max 与自定义比较器一起使用?
- 通过函数指针对类内的 STL SET 使用自定义比较器
- C#二进制编写器自定义
- QList 作为 qt 设计器自定义小部件中的一个属性
- std::sort - 正在传递错误的比较器未定义的行为