c++循环列表错误
C++ circular list error
我正在创建一个程序,它将获取n个项目的列表,然后消除每三个项目,直到只剩下一个。我得到一个错误,我的代码正在访问一个不存在的列表项。我知道我可以使用整数计数器来修改它但我更希望找到问题的根源
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;
}
这部分是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();
相关文章:
- 错误 没有与参数列表匹配的重载函数"getline"实例
- 如何防止初始值设定项列表中的错误值?
- 从类型列表中递归删除重复项会导致编译器堆空间错误 (VS2017)
- 为什么我会收到此错误?无法将 {lb, ub} 从<大括号括起来的初始值设定项列表>转换为 float(**)(float*, int)
- 错误:"模板<类_Tp,类_Dp>类 std::unique_ptr"的模板参数列表中参数 1 的类型/值不匹配
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 我将 Makefile 更改为 C++11 版本,但仍然收到列表初始值设定项错误
- 使用 C++11 时列表中出现编译错误
- 使用成员初始值设定项列表时没有匹配的函数调用错误
- 结构数组的构造函数错误,错误消息:没有构造函数实例与参数列表匹配
- 处理程序的模块列表中有一个错误的模块"WebSocketModule"
- 程序接收信号SIGSEGV,分段错误.C++列表
- 格式化输出以显示在错误列表的消息部分中
- 错误 - 列表节点未命名类型
- 错误:“列表”不是“std”的成员,错误:模板参数 2 无效
- 正在创建Visual Studio错误列表消息
- 打开 cpp 文件或视觉工作室 2013 最终剂量没有调试选项也没有错误列表
- 无法从QNetworkAccessManager访问Ssl错误列表
- 在QT中链接libCurl会给出一个庞大的C++错误列表
- Visual Studio 2012 c++构建失败,但错误列表或输出中没有任何内容