【问题标题】:Using comparison function for the key type for sets results in runtime error对集合的键类型使用比较函数会导致运行时错误
【发布时间】: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({...}, &amp;comp).
  • 不要使用整数来表示电话号码。我的(以及我所在国家/地区的大多数数字)都会失败。
  • @MikeSeymour 什么会更好?
  • @AndreasDM:std::string 可以包含任意数字序列(包括像我这样的数字,以0 开头)。如果您想将值限制为有效的电话号码,也许可以在其周围放置一个包装器。

标签: c++ c++11 set runtime-error decltype


【解决方案1】:

decltype(comp)* 只是一个指向签名为bool(Phone const&amp;, Phone const&amp;) 的函数的指针。它的值初始化为nullptrstd::multisetstd::initializer_list 构造函数将其用作 Compare 对象的默认参数。由于您已经使用空函数指针作为比较器初始化了 std::multiset,因此调用它可能会导致段错误。

要解决此问题,请提供 Compare 对象的有效实例,如下所示:

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

【讨论】:

    猜你喜欢
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多