2015-05-28 52 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}; 
相關問題