C++ C++;循环列表错误
我正在创建一个程序,它将获取n个项目的列表,然后每隔三个项目删除一个,直到只剩下1个。我的代码访问不存在的列表项时出错。我知道我可以使用整数计数器来修改它,但我更愿意找到问题的根源C++ C++;循环列表错误,c++,list,iterator,C++,List,Iterator,我正在创建一个程序,它将获取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
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;
}
intmain()
{
双重追求者=0;
int-checker=0;
内部温度=0;
做
{
求婚者;
棋盘格=求婚者;
如果(cin.fail()| | | checker!=suiters | | suiters这部分就是bug:
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();
我认为第三行应该以else开头;else如果(++I…
可以的话,但是我选择不进行优化,因为从优化的角度来说,整个算法不应该首先使用。感谢mike和wimmel,我实现了您的更改和我的计数的一个小更改,它成功了perfectly@MikeDeSimone如果i==men.end()
您将执行i=men.begin()
,然后执行++i
。