-1

我对以下代码部分有疑问。我已经对此进行了一段时间的研究,并发现问题*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");
4

2 回答 2

2

删除此行末尾的分号。

 for (pos = numbers.begin(); pos != numbers.end(); pos++) ;
于 2013-04-22T00:53:41.003 回答
2

for您的语句末尾有一个分号

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

删除它,您的代码应该可以工作。


编辑:

请注意,如果您的列表为空,则无法取消引用返回的迭代器值,这可能是您的运行时错误的原因。因此,如果您0在添加任何数字之前运行代码并立即输入,您将收到您所看到的错误。

于 2013-04-22T00:53:47.880 回答