对集合的键类型使用比较函数会导致运行时错误
Using comparison function for the key type for sets results in runtime error
我已经看了这个问题,但它没有帮助我。
我的问题是:为什么在使用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)*
只是指向签名为bool(Phone const&, Phone const&)
的函数的指针。它的值初始化为nullptr
。std::multiset
的std::initializer_list
构造函数使用this作为Compare
对象的默认参数。由于您已经将std::multiset
初始化为一个空函数指针作为比较器,因此对它的调用可能会导致段错误。
Compare
对象实例,如下所示:
multiset<Phone, decltype(comp)*> phones {{ Phone(911), Phone(112)}, &comp};
相关文章:
- 在循环中使用lower_bound函数会给出运行时错误
- 为什么在C 类构造函数的正确编译后发生运行时错误
- 为什么此函数中的运行时错误 C++ 深度优先搜索
- C 复制构造函数产生运行时错误
- 为什么当 std::sort 中的比较函数始终返回 true 时出现运行时错误
- 使用虚拟void函数的类中出现运行时错误,但没有编译错误
- 尝试将动态数组分配作为函数时出现运行时错误
- 为什么在为数组输入并输入合并排序函数后出现运行时错误
- 参数的可变数量函数运行时错误
- 具有变量参数的函数运行时错误
- 调用静态成员函数会导致运行时错误
- 在纯虚拟类的析构函数中等待线程死亡会导致运行时错误
- 打印字符串时出现运行时错误,即使它在函数中运行良好
- C++析构函数运行时错误:无法munmap
- 函数从字符串转换为int时出现运行时错误
- 成员函数指针运行时错误——ESP的值在函数调用中没有正确保存
- 我需要写一个函数,将十六进制转换为十进制,并使用递归,我不断得到运行时错误
- GetOpenFileName和系统函数调用运行时错误c++ win32 api
- 使用引用函数调用时出现运行时错误
- C++回调函数运行时错误