2015-05-28 53 views
1

我已阅读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编译都导致相同。

+0

[在C++初始化用定制的比较函数多重集]的可能重复(http://stackoverflow.com/questions/18718379 /初始化 - multiset与自定义比较功能在c) – NathanOliver

+0

你需要给它一个'decltype(comp)*'的实例。例如。 '电话({...},&comp)'。 –

+0

请勿使用整数表示电话号码。这对我的(以及我国大部分的数字)都会失败。 –

回答

2

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}; 
相关问题