开发者

Segfault on using transform on a vector of pointers to an abstract class

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(res开发者_JS百科ults.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?


The results vector is empty, and transform 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:

std::vector<bool> results(v.size());

or use a "back insert" iterator to push the results onto the empty vector:

std::transform(v.begin(), v.end(), std::back_inserter(results), std::mem_fun(&A::Ok));


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 at results.begin() is a pretty dumb thing to do. Instead, use std::back_inserter(results) and everything works fine!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜