c++向量:插入时出现段错误

发布于 2024-10-14 19:26:48 字数 893 浏览 1 评论 0原文

以下代码在到达插入语句时出现段错误:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

独享拥抱 2024-10-21 19:26:48

如果getStrand()返回一个向量按值,则sit2eit2是迭代器放入向量的不同副本中,一旦获得迭代器,两个副本都会被销毁。您需要通过引用返回向量,或者保存向量的副本并从该副本获取迭代器。

If getStrand() returns a vector by value, then sit2 and eit2 are iterators into different copies of the vector, and both copies are destroyed as soon as you obtain the iterators. You need either to return the vector by reference or save the copy of the vector and obtain iterators from that one copy instead.

仲春光 2024-10-21 19:26:48

我的猜测是 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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文