简体   繁体   English

C ++“列表迭代器错误”

[英]C++ “list iterator error”

I'm having a problem with the following section of code. 我在以下代码段中遇到问题。 I've worked with this for a bit and have found the issue comes in *pos is added. 我已经使用了一段时间,发现问题出现在*pos中。 I'm just not sure how to fix it. 我只是不确定如何解决它。

#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++) ;

You have a semicolon at the end of your for statement 您的for语句结尾处有分号

for (pos = numbers.begin(); pos != numbers.end(); pos++) ;
                                                        ^^^

Remove that and your code should work. 删除它,您的代码应该可以工作。


EDIT: 编辑:

Note that if your list is empty, the returned iterator value cannot be dereferenced, which could be the cause of your runtime error. 请注意,如果列表为空,则无法取消对返回的迭代器值的引用,这可能是导致运行时错误的原因。 So if you run your code and enter 0 immediately before adding any numbers, you'll get the error you're seeing. 因此,如果您运行代码并在添加任何数字之前立即输入0 ,则将收到所看到的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM