Using Lists

Hello everyone,

I am having interesting issue here. If I run the following code program crashes. I just wanted to print the list using comma between elements... If you could please tell me whats wrong here, thatd be very nice of you :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 #include <list>
#include <iostream>

using namespace std;

int main()
{
	list <int> A;
	list <int> B;
	int i,j;
	cin>>i;
	while(i>0) {
		A.push_back(i);
		cin>>i;
	}
	cin>>j;
	while(j>0) {
		B.push_front(j);
		cin>>j;
	}
	list<int>::const_iterator liter;
        while (liter != A.end()) {
		if(liter == A.begin()) {
			cout << *liter;
		} else {
			cout <<","<< *liter;
		}
		++liter;
	}
}
Last edited on
The first problem I see is that you are not initializing liter. Take a look at the example here on http://www.cplusplus.com/reference/list/list/push_front/ and see that the iterator is initialized as the beginning of the actual list. In your case, list<int>::const_iterator liter=A.begin();
Thanks, I got it!
Topic archived. No new replies allowed.