[英]C++ “list iterator error”
我在以下代码段中遇到问题。 我已经使用了一段时间,发现问题出现在*pos
中。 我只是不确定如何解决它。
#include <iostream>
#include <list>
#include <string>
using namespace std;
list<int>:: iterator pos; //iterator for pos to allow movement through the list
list<int> numbers; // list of int's called "numbers"
int a; // @param a: int to store value at the current position in the list for comparison
int b = 0; // @param b: int to store larger value after comparison
/*function maximum cycles through the list of numbers and assigns the number at each position to variable a
variable a is then compared to variable b which holds the largest element, if variable a is larger than b then
variable a's value is given to b.
*/
int maximum()
{
for (pos = numbers.begin(); pos != numbers.end(); pos++)
{
a = *pos;
if (a > b)
{
b = a;
}
}
return b;
}
int main()
{
int UserNum; //@param UserNum are the numbers the user will enter that will be added to the list
//A do loop to fill the list with numbers entered by the user.
cout << "Enter some numbers (0 to end)" << endl;
do
{
cin >> UserNum;
numbers.push_back (UserNum);
}
while (UserNum);
maximum();
cout << ("Your largest element entered is ") << b << endl;
system ("PAUSE");
从该行的末尾删除分号。
for (pos = numbers.begin(); pos != numbers.end(); pos++) ;
您的for
语句结尾处有分号
for (pos = numbers.begin(); pos != numbers.end(); pos++) ;
^^^
删除它,您的代码应该可以工作。
编辑:
请注意,如果列表为空,则无法取消对返回的迭代器值的引用,这可能是导致运行时错误的原因。 因此,如果您运行代码并在添加任何数字之前立即输入0
,则将收到所看到的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.