gpt4 book ai didi

c++ 创建新对象时 : iterator not incrementable

转载 作者:行者123 更新时间:2023-11-28 00:30:38 33 4
gpt4 key购买 nike

我正在处理一项任务,要创建一群兔子,它们可以在每一轮中繁殖。所以我定义了一个Bunny类(个体),然后定义了一个Troop类, vector 指向不同的兔子。我的问题是,每次我使用 new 在循环中创建对象 Bunny 时,都会出现错误:

“调试断言失败!!... vector 迭代器不可递增...”

这是我的代码示例:

class Bunny {
private:
string sex;
string color;
string name;
int age;
public:
string getname() { return name;};
Bunny(); // constructor
};

class Troop {
private:
vector<Bunny *> bunpointer;
vector<Bunny *>::iterator it;
public:
void newbunny();
void multiply();
};

void Troop::newbunny() {
Bunny * bun; // pointer to the Bunny class
bun = new Bunny;
cout << "Bunny " << bun->getname() << " is born! \n";
bunpointer.push_back(bun);
}

void Troop::multiply() {
it = bunpointer.begin();
while(it!=bunpointer.end()) {
cout << (*it)->getname() << " gave a birth. ";
newbunny();
++it;
}
it = bunpointer.begin();
}

因此,如果我一开始创建 5 个兔子,并调用函数 Troop::multiply,则应该有 10 个兔子。一个有趣的观察是,错误会在 2 只兔子出生后发生。

我认为问题可能在于使用 new 在迭代器循环中创建新对象。 new 可能会以某种方式中断迭代器指针 *it。但我不确定是否是这种情况,如果真的是,如何处理。

修改:原来是使用push_back()的问题,很可能会使iterator失效!!

提前致谢!

最佳答案

1) 除非你有理由,否则你的代码根本不需要使用 new。代码变得更简单,并且没有内存泄漏的机会。另外,我认为 Troop 类中不需要迭代器成员,除非您能证明这样做的理由。

2) 至于您眼前的问题,只需使用非迭代器依赖循环。换句话说,一个从 0 到当前兔子数减 1 的简单循环。

这是一个例子:

#include <vector>
//...
class Troop {
private:
std::vector<Bunny> bunpointer;
public:
void newbunny();
void multiply();
};

void Troop::newbunny() {
bunpointer.push_back(Bunny());
}

void Troop::multiply() {
size_t siz = bunpoiner.size();
for (size_t i = 0; i < siz; ++i ) {
newbunny();
cout << (*it)->getname() << " gave a birth. ";
}
}

newbunny() 函数只是使用默认构造函数创建一个 Bunny() 并将项目添加到 vector 中。

如果您想使用一个在插入项时不会使迭代器无效的容器,那么您可以使用 std::list 而不是 std::vector.

关于c++ 创建新对象时 : iterator not incrementable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23050627/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com