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?
The
resultsvector is empty, andtransformdoes not know that you want the results pushed onto it rather then overwriting an existing sequence.Either initialise the
resultsvector with the correct size:or use a “back insert” iterator to push the results onto the empty vector: