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編譯都導致相同。
[在C++初始化用定製的比較函數多重集]的可能重複(http://stackoverflow.com/questions/18718379 /初始化 - multiset與自定義比較功能在c) – NathanOliver
你需要給它一個'decltype(comp)*'的實例。例如。 '電話({...},&comp)'。 –
請勿使用整數表示電話號碼。這對我的(以及我國大部分的數字)都會失敗。 –