【发布时间】:2014-08-23 20:42:43
【问题描述】:
我正在创建一个程序,它将获取 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;
}
【问题讨论】: