使用迭代器时遇到问题,每 M 次传递一次擦除一个向量项



我在实现向量时遇到了一些问题。我尝试制作的程序如下:获取用户定义的"size"值并创建该大小的"圆形"向量。然后,它接受另一个整数变量,该变量表示在从向量中删除项之前必须进行多少次循环迭代。在我的代码中,我试图遍历这个"Person"对象向量(一个基本类,其唯一的私有数据成员是表示位置的整数)。声明此"runProgram"函数的类具有 person 对象向量的私有数据成员,然后是三个整数,分别表示圆圈大小、消除前的传递次数以及向量中的项目数。 我已经做了一段时间循环来执行此过程。但是,每次我运行这个程序时,该程序似乎只通过循环一次,然后删除所有内容......或者只是不继续。这是我的一些代码:

主循环:

enter cod int VectorMyJosephus::runProgram(){
int n = 0;
int m = 0;
cout << "How many people would you like in the circle?" << endl;
cin >> n;
cout << "How many passes would you like ther to be before someone is eliminated?" << endl;
cin >> m;
init(n, m);
vector<Person>::iterator iter;
iter = circ.begin();
int count = 0;
while (circ.size() > 1)
{
//count the current person
count += 1;
iter->print();
//remove every "M" person
if (count == M)
{
iter = circ.erase(iter);
count = 0;
size -= 1;
/*printAll();
system("PAUSE");*/
}
else
{
//contine through the list once someone was removed
++iter;
}
if (iter == circ.end())
{
iter = circ.begin();
}

cout << "The position of the only remaining person is: " << iter->getPosition() << "n" << endl;
cout << circ.size() << endl;

return 0;
}

}e 这里

这是我的初始化函数,它应该用 person 对象填充向量:

void VectorMyJosephus::init(int N, int M)
{
this->setN(N);
this->setM(M);
this->setSize(N);
for (int i = 0; i < N; i++)
{
Person pers;
pers.setPosition(i);
circ.push_back(pers);
}
}

我是初学者,所以任何帮助都非常感谢

你在 while 循环中return 0了,这会立即中断循环执行。

最新更新