【发布时间】:2015-05-29 00:41:15
【问题描述】:
我已阅读this 问题,但对我没有帮助。
我的问题是:为什么在为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)*的实例。例如。phones({...}, &comp). -
不要使用整数来表示电话号码。我的(以及我所在国家/地区的大多数数字)都会失败。
-
@MikeSeymour 什么会更好?
-
@AndreasDM:
std::string可以包含任意数字序列(包括像我这样的数字,以0开头)。如果您想将值限制为有效的电话号码,也许可以在其周围放置一个包装器。
标签: c++ c++11 set runtime-error decltype