对指向抽象类的指针向量使用变换时出现的段错误
我在以下代码中遇到段错误:
我有一个带有方法的抽象类 A
virtual bool Ok() const;
现在,我有以下向量,
std::vector<A*> v;
其中填充了多个指向现有子对象的指针。我想累积 Ok()
方法的结果,如下所示:
std::vector<bool> results;
std::transform(v.begin(), v.end(), results.begin(), std::mem_fun(&A::Ok));
std::accumulate(results.begin(), results.end(), true, std::logical_and<bool>());
不幸的是,我总是在第二行出现段错误,我不明白为什么。用标准 C++ 循环替换转换调用可以修复段错误。有什么想法吗?
I experience a segfault on the following code:
I have an abstract class A
with a method
virtual bool Ok() const;
Now, I have the following vector
std::vector<A*> v;
filled with several pointers to existing child objects. I want to accumulate the results of the Ok()
method as follows:
std::vector<bool> results;
std::transform(v.begin(), v.end(), results.begin(), std::mem_fun(&A::Ok));
std::accumulate(results.begin(), results.end(), true, std::logical_and<bool>());
Unfortunately, I always get a segfault on the second line, and I do not understand why. Replacing the transform call by a standard C++ loop fixes the segfault. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
results
向量为空,并且transform
不知道您希望将结果推送到它上面,而不是覆盖现有序列。使用正确的大小初始化结果向量:
或者使用“后插入”迭代器将结果推送到空向量上:
The
results
vector is empty, andtransform
does not know that you want the results pushed onto it rather then overwriting an existing sequence.Either initialise the
results
vector with the correct size:or use a "back insert" iterator to push the results onto the empty vector:
这可能很愚蠢,但我会直接回答我自己的问题。我在点击“发布你的问题”之前不久就发现了问题,并发现,由于我已经输入了所有内容,我也可能会发布答案,这样其他人可能会从中受益:
答案是,
结果< /code> 向量是空的,因此在
results.begin()
处插入是一件非常愚蠢的事情。相反,使用 std::back_inserter(results) 一切正常!It might be stupid, but I will answer my own question directly. I found the problem shortly before clicking on "post your question" and figured that, since I typed everything already, I might also post the answer, so that someone else might benefit from it:
The answer is, that the
results
vector is empty and hence inserting atresults.begin()
is a pretty dumb thing to do. Instead, usestd::back_inserter(results)
and everything works fine!