c++ transform with pair get Segmentation fault
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&l开发者_如何学Pythont;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 transform
is expecting results
object to have the required memory allocated i.e. it is expecting results.size()
is atleast as big as tests.size()
. If you want to push_back operation to be performed on the results
then you should use std::back_inserter(results)
as the third argument. Otherwise, when transform
uses the *
output iterator you passed, it will be a invalid memory location and will result in a segmentation fault.
精彩评论