【问题标题】:C++ iterator not derefancableC ++迭代器不可取消
【发布时间】:2014-12-10 13:08:10
【问题描述】:

我是 C++ 新手,我尝试做 The Bunny 练习,但我的代码有一些问题,请看一下这段代码: 错误是向量迭代器不可取消引用 // 和 // 标准库超出范围。 谢谢你帮助我!

void  GameUpdate()
{   
vector<Iepuras>::iterator it;
vector<Iepuras>::iterator i;
bool ExistaTata=false; // dad exist
    i = Lista.begin();
while (!ExistaTata && i != Lista.end()) // dad exist

    if (i->Varsta >2 && i->Sex == "Male")
    {
        ExistaTata = true; //dad exist
        i++;
    }
else 
{
    i++;
}
for (it = Lista.begin(); it != Lista.end();it++)
{
    it->Varsta++;  // age ++ 
    it->title = it->Sex + " " + it->Nume + " "+ it->Color + " " + to_string(static_cast<long long>(it->Varsta));
    if (it->Varsta >2 && it->Sex == "Female")  // if age > 2 and female
        if (ExistaTata)   // if dad exist
        {  // new bunny
            Iepuras *f;
            f = new Iepuras;
            Lista.push_back(*f);
        }
    while (it->Varsta>10) // if age > 10 erase bunny
    {
        it = Lista.erase(it);

    }
}

}

【问题讨论】:

  • 您不需要new 来创建新的“兔子”(在您的情况下会导致内存泄漏),只需编写List.push_back(Iepuras()) 或Iepuras f; Lista.push_back(f);。

标签: c++


【解决方案1】:

我认为问题的原因是以下循环

while (it->Varsta>10) // if age > 10 erase bunny
{
    it = Lista.erase(it);

}

在此循环之后,它可以等于 Lista.end()(并且在您尝试访问数据成员的此循环的条件下),然后您在封闭循环中增加它

for (it = Lista.begin(); it != Lista.end();it++)

也许我弄错了,但我没有看到在第一个循环之后使用迭代器 i 的位置。所以我认为在循环外声明迭代器没有任何意义。

考虑到这些语句会导致内存泄漏

    if (ExistaTata)   // if dad exist
    {  // new bunny
        Iepuras *f;
        f = new Iepuras;
        Lista.push_back(*f);
    }

因为对象 *f 的副本将被放置在向量中。因此对象 *f 被分配但没有被删除。你可以简单地写

        Lista.push_back( Iepuras() );

也不要用这种手鼓跳舞

bool ExistaTata=false; // dad exist
    i = Lista.begin();
while (!ExistaTata && i != Lista.end()) // dad exist

    if (i->Varsta >2 && i->Sex == "Male")
    {
        ExistaTata = true; //dad exist
        i++;
    }
else 
{
    i++;
}

我建议使用标头&lt;algorithm&gt; 中声明的标准算法std::any_of 在这种情况下,您的代码会更清晰。 我认为你应该完全重写这个函数。

【讨论】:

  • 非常感谢,我会根据你的建议重写函数。
猜你喜欢
  • 1970-01-01
  • 2015-01-13
  • 1970-01-01
  • 2018-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多