[英]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.