c++向量:插入时出现段错误
以下代码在到达插入语句时出现段错误:
rna* annealer::anneal(rna strand1, rna strand2, const rna & opponent){
std::vector<nukleotid*>::iterator sit2;
std::vector<nukleotid*>::iterator eit2;
std::vector<nukleotid*>::iterator eit;
if(tryAnneal(strand1, strand2, opponent)) {
eit = strand1.getStrand().end();
sit2 = strand2.getStrand().begin();
eit2 = strand2.getStrand().end();
//here be segfault
strand1.getStrand().insert(eit, sit2, eit2);
strand1.isAnnealed = true;
rna* str = &strand1;
std::cout << *str << std::endl;
return str;
}
//...
return NULL;
}
rna 包含一个向量,该向量由 getStrand() 返回。
它让我发疯。我真的不明白为什么会出现段错误。代码的一个稍微不同的版本,其中 in 没有声明新的迭代器,而只是将 strand1.getStrand().end();
(以及另外两个)传递给 vector::insert( )直接抛出了一个 length_error ,这也没有任何意义,因为我的向量很小(〜10个元素)。
谁能看到我在这里做错了什么吗?
The folowing code is giving a segfault when reaching the insert statement:
rna* annealer::anneal(rna strand1, rna strand2, const rna & opponent){
std::vector<nukleotid*>::iterator sit2;
std::vector<nukleotid*>::iterator eit2;
std::vector<nukleotid*>::iterator eit;
if(tryAnneal(strand1, strand2, opponent)) {
eit = strand1.getStrand().end();
sit2 = strand2.getStrand().begin();
eit2 = strand2.getStrand().end();
//here be segfault
strand1.getStrand().insert(eit, sit2, eit2);
strand1.isAnnealed = true;
rna* str = &strand1;
std::cout << *str << std::endl;
return str;
}
//...
return NULL;
}
rna contains a vector, which is returned by getStrand().
Its driving me crazy. I really cant understand why theres a segfault. A slightly different version of the code, in which in didnt declare new iterators, but was just passing strand1.getStrand().end();
(and the two other), to vector::insert() derictly threw a length_error which does not make any sense either, as my vectors are small (~10 elements).
can anyone see what am i doing wrong here?`
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果
getStrand()
返回一个向量
按值,则sit2
和eit2
是迭代器放入向量的不同副本中,一旦获得迭代器,两个副本都会被销毁。您需要通过引用返回向量
,或者保存向量
的副本并从该副本获取迭代器。If
getStrand()
returns avector
by value, thensit2
andeit2
are iterators into different copies of thevector
, and both copies are destroyed as soon as you obtain the iterators. You need either to return thevector
by reference or save the copy of thevector
and obtain iterators from that one copy instead.我的猜测是 getStrand 返回向量的副本,而不是对其的引用。这将导致您正在使用的迭代器(eit、sit2 等)在创建后立即变得无效!
您可以粘贴该方法的声明吗?
My guess is that getStrand is returning a copy of the vector, instead of a reference to it. That will cause the iterators you're using (eit, sit2, and so on) to become invalid immediately after they're created!
Can you paste your declaration for that method?