对集合的键类型使用比较函数会导致运行时错误

Using comparison function for the key type for sets results in runtime error

我已阅读 this 问题,但它对我没有帮助。

我的问题是:为什么在对 set 的键类型使用比较函数时出现运行时错误,如下所示?

multiset<Phone, decltype(comp)*> phones { Phone(911), Phone(112) };
              //^^^^^^^^^^^^^^^

在 VC2013 中,上面的代码给出了这个:

Unhandled exception at 0x73DECB49 in debugit.exe: 0xC0000005: Access violation executing location 0x00000000.

这是一个产生错误的小例子:

#include <iostream>
#include <algorithm>
#include <string>
#include <set>
using namespace std;

struct Phone {
    Phone(long long const &num) : number{num} {}
    long long number;
};

// compare function:
bool comp(Phone const &n1, Phone const &n2) { return n1.number < n2.number; }

int main()
{   // The below line produces the runtime error.
    multiset<Phone, decltype(comp)*> phones { Phone(911), Phone(112) };
}

我看不出我做错了什么。我用 VC2013 和 g++ (GCC) 4.9.1 编译结果相同。

decltype(comp)* 只是指向具有签名 bool(Phone const&, Phone const&) 的函数的指针。它的值初始化为 nullptrstd::multisetstd::initializer_list 构造函数使用它作为 Compare 对象的默认参数。由于您已经使用空函数指针作为比较器初始化了 std::multiset,因此调用它可能会导致段错误。

要解决此问题,请像这样提供 Compare 对象的有效实例:

multiset<Phone, decltype(comp)*> phones {{ Phone(911), Phone(112)}, &comp};