This code works:
class Test
{
public:
Test(string name) : _name(name) {};
bool operator()() { cout << "hello " << _name << endl; return true; }
string name() { return _name; }
private:
string _name;
};
pair<string, bool>
inline execute_test(Test* t) {
return pair<string, bool>(t->name(), (*t)());
}
int main()
{
vector<Test*> tests;
vector<pair<string, bool> > results;
tests.push_back(new Test("Test1"));
tests.push_back(new Test("Test2"));
for (unsigned int i=0; i < tests.size(); ++i)
results.push_back(execute_test(tests[i]));
}
now I want to use trasform instead of the for cicle:
transform(tests.begin(), tests.end(),
results.begin(),
execute_test);
but I got a Segmentation Fault. Where is the problem?
That is because
transformis expectingresultsobject to have the required memory allocated i.e. it is expectingresults.size()is atleast as big astests.size(). If you want to push_back operation to be performed on theresultsthen you should usestd::back_inserter(results)as the third argument. Otherwise, whentransformuses the*output iterator you passed, it will be a invalid memory location and will result in a segmentation fault.