2013-05-13 49 views
1

通过浪费更多时间在我的代码上,我越来越困惑。我只想要迭代器的内容,而不是它的地址。这里是我的代码:不是我想要的内容的地址?

Peptides tempPep; 
tempPep.set_PEPTIDE("AABF"); 
std::vector<Peptides>::iterator itPep = std::find_if (this->get_PepList().begin(), this->get_PepList().end(),boost::bind(&Peptides::Peptide_comparison, _1,tempPep)); 
if (itPep != this->get_PepList().end()) 
{ 

    Spectra tempSp; 
    tempSp.set_Charge(1127); 
    tempSp.set_Snum(1); 
    std::cout << "without iterator "<< this->get_PepList()[0].get_New_S_num() << std::endl; 
    // output -> 0 
    std::cout << "with iterator" << itPep->get_New_S_num() <<std::endl; 
    //output -> 1129859637 
} 
+1

是什么'get_PepList()'返回副本或引用?当呼叫返回的向量已过期时,itPep可能是悬而未决的。 – 2013-05-13 20:11:32

+0

在C++类型是至关重要的。什么是Peptides,什么是这个''的类型以及'get_PepList()'和'get_New_S_num()'是如何工作的。 – 2013-05-13 20:17:01

回答

2

试着改变你的代码如下:

std::vector<Peptides> p = this->get_PepList(); 
std::vector<Peptides>::iterator itPep = std::find_if (p.begin(), 
    p.end(),boost::bind(&Peptides::Peptide_comparison, _1,tempPep)); 
+0

谢谢!你能再详细描述一下吗? – khikho 2013-05-14 18:08:38

+1

@khikho:从'this-> get_PepList()'返回的向量的生命周期在该行的末尾到达对'std :: find_if'的调用,因为您称它为'this-> get_PepList()。 ()'。这意味着'itPep'持有迭代器到一个不再存在的向量中。为了确保向量保持有效,我更改了代码以将从'get_PepList()'返回的向量复制到变量中,即'std :: vector p = this-> get_PepList();'。这确保了当你用'itPep'迭代器访问它的一个元素时,vector仍然在。 – 2013-05-14 20:40:16

1

如果你想要的内容,指向它:*itPep

迭代器重载*操作并返回数据。 (感谢修正,我不知道!)

+0

'itPep'不是直接的地址。迭代器重载'*'运算符并从那里返回数据。 – 2013-05-13 20:08:09

+0

谢谢@ Magtheridon96! – 2013-05-13 20:09:22

+0

此外,您可以用\'\'围绕一段文本,让它像代码一样显示。 ; p(我会为你编辑这个) – 2013-05-13 20:10:41