开发者

c++ transform with pair get Segmentation fault

开发者 https://www.devze.com 2022-12-21 21:00 出处:网络
This code works: class Test { public: Test(string name) : _name(name) {}; bool operator()() { cout << \"hello \" << _name << endl; return true; }

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.

0

精彩评论

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

关注公众号