Trouble with lists
This is my program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <iostream>
#include <list>
int main ()
{
std::list<int> intList {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (auto iter = intList.begin (); iter != intList.end (); ++iter)
{
if (*iter == 5)
{
intList.erase (iter);
}
std::cout << *iter << std::endl;
}
int x;
std::cin >> x;
return 0;
}
|
From what I understand, it should output:
1 2 3 4 5 6 7 8 9
|
1
2
3
4
6
7
8
9
10
|
Instead, it seems to miss the end of the list and keeps outputting large numbers extremely quickly. What did I do wrong?
You shall write
iter = intList.erase (iter);
Or you can use member function
remove . For example
1 2 3
|
std::list<int> intList {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
intList.remove( 5 );
|
Last edited on
Topic archived. No new replies allowed.