c++ std::set 插入导致分段错误
所有-
我不太明白为什么这段代码会导致分段错误......任何帮助都会很棒。
#include <iostream>
#include <set>
using namespace std;
class A{
public:
int _x;
A(int x){
_x = x;
}
};
bool fncomp(A a1, A a2){
return a1._x < a2._x;
}
int main(){
bool(*fn_pt)(A,A) = fncomp;
set<A, bool(*)(A,A)> testSet;
for(int i=0; i<10; i++){
cout << i << endl;
A a(i);
testSet.insert(a);
}
}
输出是:
0
1
Segmentation Fault
All-
I can't quite figure out why this piece of code is resulting in a segmentation fault... Any help would be great.
#include <iostream>
#include <set>
using namespace std;
class A{
public:
int _x;
A(int x){
_x = x;
}
};
bool fncomp(A a1, A a2){
return a1._x < a2._x;
}
int main(){
bool(*fn_pt)(A,A) = fncomp;
set<A, bool(*)(A,A)> testSet;
for(int i=0; i<10; i++){
cout << i << endl;
A a(i);
testSet.insert(a);
}
}
The output is:
0
1
Segmentation Fault
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,看看你的代码。您声明了一个函数
fncomp
,但您真的在任何地方使用该函数吗?您用它初始化fn_pt
,但fn_pt
没有在任何地方使用。你不觉得很奇怪吗?如果您从未要求您的 set 对象使用该函数,您如何期望您的testSet
对象知道您希望它使用您的fncomp
作为比较器?您使用普通函数指针类型
bool(*)(A,A)
声明集合testSet
作为比较器类型。这是比较器的类型。现在,您必须通过构造函数参数将比较器的实际值传递给您的设置对象(
您实际上并不需要中间指针
fn_pt
)。您忘记这样做了,并且 set 对象使用了比较器的默认构造函数参数值,在本例中为空指针。因此,每次
testSet
对象尝试比较两个元素时,它都会通过空指针执行函数调用。难怪会崩溃。Well, look at your code. You declared a function
fncomp
, but are you really using that function anywhere? You initializefn_pt
with it, butfn_pt
is not used anywhere. Doesn't it seem strange to you? How do you expect yourtestSet
object to know that you want it to use yourfncomp
as the comparator, if you never ask your set object to use that function?You declared your set
testSet
with an ordinary function pointer typebool(*)(A,A)
as a comparator type. That's the type of the comparator. Now, you have to pass the actual value of the comparator to your set object through the constructor parameteror
(You don't really need that intermediate pointer
fn_pt
).You forgot to do that, and the set object used the default constructor argument value for the comparator, which in this case is a null pointer. So, every time your
testSet
object tries to compare two elements, it performs a function call through a null pointer. No wonder it crashes.您没有收到有关未使用变量
fn_pt
的编译器警告吗?变量
testSet
有一个指定类型bool(*)(A,A)
的内部比较器。由于您没有初始化它,因此它默认初始化为 NULL。因此,当 testSet 尝试插入 A(1) 时,它会尝试调用空函数指针来确定哪个顺序是正确的。你的意思可能是:
Didn't you get a compiler warning about the unused variable
fn_pt
?The variable
testSet
has an internal comparator of the specified typebool(*)(A,A)
. Since you didn't initialize it, it was default initialized as NULL. So whentestSet
tried to insertA(1)
, it tried to invoke a null function pointer to figure out which order is correct.You probably meant: