std :: set与自定义比较器

时间:2018-10-30 18:44:27

标签: c++ data-structures set

我正在尝试按集合中wordCount降序对wordItem进行排序。

我处于数据结构中,我们的教授给我们提出了在以前的作业中使用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结构混在一起非常麻烦,但是任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

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

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