为什么在声明std::set时需要重复排序子程序

Why do I need to repeat the sorting subroutine when declaring a std::set?

本文关键字:子程序 排序 声明 std set 为什么      更新时间:2023-10-16

在我的C++程序中,我试图按值而不是按键对映射进行排序。

从这个问题来看,很明显,实现这一点的方法是创建一个集合,该集合的元素是成对的,并且由我自己的小于函数排序。

以下是我尝试这样做的一些示例代码:

#include <map>
#include <set>
#include <iostream>
#include <string>
using namespace std;
bool compareCounts(const pair<string, size_t> &lhs, const pair<string, size_t> &rhs);
int main (int argc, char *argv[]) {
        map <string, size_t> counter = { {"A", 1}, {"B", 2}, {"C", 3} };
        set <pair<string, size_t>, decltype(compareCounts) *> sorted_counter;
        for (map<string, size_t>::iterator it = counter.begin(); it != counter.end(); ++it) {
                cout << "About to add: " << it->first << ":" << it->second << endl;
                auto ret = sorted_counter.insert(*it);
                if (! ret.second) {
                        cout << "ERROR adding this element!" << endl;
                } else {
                        cout << "Element added ok" << endl;
                }
                cout << "Set is of size: " << sorted_counter.size() << endl;
        }
        return 0;
}
bool compareCounts(const pair<string, size_t> &lhs, const pair<string, size_t> &rhs) {
        return lhs.second > rhs.second;
}

这是输出:

即将添加:A:1
元素添加正常
套装大小为:1
即将添加:B:2
分段故障:11

当我添加第二个元素时,我注意到事情会崩溃。我发现发生这种情况是因为现在有必要调用我的排序子程序compareCounts

修复方法是更改这条线:

set <pair<string, size_t>, decltype(compareCounts) *> sorted_counter;

到此:

set <pair<string, size_t>, decltype(compareCounts) *> sorted_counter(compareCounts);

为什么我需要指定两次排序子程序compareCounts?编译器不是已经从我的类型定义中知道了吗?

set <pair<string, size_t>, decltype(compareCounts) *> sorted_counter;

您从未指定set实际应该使用什么比较器。将以上行更改为

set <pair<string, size_t>, decltype(compareCounts) *> sorted_counter(compareCounts);

在没有指定比较器的情况下,set默认构造一个(nullptr),当它试图使用比较器插入第二个元素时,代码会崩溃。

你应该只使用一个函子而不是一个函数指针

struct compareCounts
{
    bool operator()(const pair<string, size_t> &lhs, 
                    const pair<string, size_t> &rhs) const
    {
        return lhs.second > rhs.second;
    }
};
set <pair<string, size_t>, compareCounts> sorted_counter;