c++与pair进行变换得到分段错误
这段代码的工作原理:
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]));
}
现在我想使用 trasform 而不是 for cicle:
transform(tests.begin(), tests.end(),
results.begin(),
execute_test);
但我遇到了分段错误。问题出在哪里?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为
transform
期望results
对象分配所需的内存,即它期望results.size()
至少与 <代码>tests.size()。如果您想对结果
执行push_back操作,那么您应该使用std::back_inserter(results)
作为第三个参数。否则,当transform
使用您传递的*
输出迭代器时,它将是无效的内存位置,并会导致分段错误。That is because
transform
is expectingresults
object 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 theresults
then you should usestd::back_inserter(results)
as the third argument. Otherwise, whentransform
uses the*
output iterator you passed, it will be a invalid memory location and will result in a segmentation fault.