【发布时间】: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++