tags:

views:

38

answers:

2

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?

+2  A: 

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!

lytenyn
You can also mark your answer as the correct one.
MKroehnert
Resizing results and using `begin()` would be alright aswell. Remember that there are a lot of things wrong with `vector<bool>`.
pmr
+2  A: 

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));
Mike Seymour
Thanks. Turns out, my own explanation was pretty confused and wrong. You are perfectly right, of course!
lytenyn
I found out how to correct my own explanation. I will mark your answer as the correct one, once I can do so, of course.
lytenyn