简体   繁体   中英

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. 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 (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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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