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

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

本文关键字:函数 运行时错误 比较 集合 类型      更新时间:2023-10-16

我已经看了这个问题,但它没有帮助我。

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

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

在VC2013中,它给了我上面的代码:

debugit.exe中0x73DECB49的未处理异常:0xC0000005:访问冲突执行位置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构造函数使用this作为Compare对象的默认参数。由于您已经将std::multiset初始化为一个空函数指针作为比较器,因此对它的调用可能会导致段错误。

要解决这个问题,提供一个有效的Compare对象实例,如下所示:
multiset<Phone, decltype(comp)*> phones {{ Phone(911), Phone(112)}, &comp};