我正在创建一个程序,它将获取n个项目的列表,然后消除每个第三个项目,直到只剩下1个项目。我收到一个错误,我的代码访问不存在的列表项。我知道我可以使用整数计数器修改它,但我更愿意找到问题的根源
int main()
{
double suitors=0;
int checker=0;
int temp=0;
do
{
cout << "How many suitors are there, min of 4 \n";
cin >> suitors ;
checker=suitors;
if (cin.fail()||checker!=suitors||suitors<4)
{
cout << "You have entered an invalid input.\n";
cin.clear();
cin.ignore(100, '\n');
suitors=-1;
}
}
while (checker!=suitors||suitors<4);
list<int> men;
for (int j=1; j<=suitors; j++)
{
men.push_back(j);
}
list<int>::iterator i;
i=men.begin();
for (int j=1; j<suitors;j++)
{
temp=0;
while (temp<3)
{
temp=temp+1;
if (temp==3)
{
cout << "Suitor #" << *i << " is eliminated \n";
i=men.erase(i);
break;
}
if (i!=men.end())
{
i++;
}
else //this is trying to reset the iterator to the start when it hits the end
{
i=men.begin();
}
}
}
i=men.begin();
cout << "If there are " << suitors
<< " then the winner will be suitors #" << *i << endl;
return 0;
}
答案 0 :(得分:1)
这部分是错误:
if (i!=men.end())
{
i++;
}
else //this is trying to reset the iterator to the start when it hits the end
{
i=men.begin();
}
如果i
指向列表的最后一项,那么它将采用i != men.end()
路由,执行++i
,然后在下一次循环中执行i == men.end()
正确的代码是:
if(i == men.end())
i = men.begin();
if(++i == men.end())
i = men.begin();