Iterators

This question is about iterators. I declare an iterator in a code and use it for printing some conatiner class object like a list for example. Then I change the list by moving its first element to the back. Next I want to print the modified list object again using an iterator, do I need to declare a new iterator?
Nope, you can reuse it.

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
31
32
33
34
35
#include <iostream>
#include <vector>
#include <ctime>
#include <algorithm>

int main(int argc, const char* argv[])
{
   std::vector<int> myVector;
   srand(time(NULL));
   
   for (int i=0; i < 10; ++i)
   {
      myVector.push_back(rand() % 100 + 1);
   }	

   std::vector<int>::iterator iter;
   
   std::cout << "Unsorted: ";
   for (iter = myVector.begin(); iter != myVector.end(); ++iter)
   {
      std::cout <<  "\t" << *iter;
   }
   std::cout << std::endl;
   
   std::sort(myVector.begin(), myVector.end());
   
   std::cout << "Sorted: ";
   for (iter = myVector.begin(); iter != myVector.end(); ++iter)
   {
      std::cout <<  "\t" << *iter;
   }
   std::cout << std::endl;
   
   return 0;
}
Ok, but what about here:
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <list>
#include <iostream>

using namespace std;

int main()
{
	list <int> A;//created two lists
	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 liter1=A.begin();
	list<int>::const_iterator liter2=B.begin();
	for(liter1=A.begin(); liter1!=A.end(); ++liter1) {
		cout<<*liter1<<" ";
	}
	cout<<endl;
	for(liter2=B.begin(); liter2!=B.end(); ++liter2) {
		cout<<*liter2<<" ";
	}
	cout<<endl<<endl;//empty line
	A.push_back(A.front());
	A.pop_front();
	B.push_back(B.front());
	B.pop_front();
	//list<int>::const_iterator liter3=A.begin();
	//list<int>::const_iterator liter4=B.begin();/
	while (liter1 != A.end()) {
		if(liter1 == A.begin()) {
			cout << *liter1;
		} else {
			cout <<","<< *liter1;
		}
		++liter1;
	}
	cout<<endl;
	
	while (liter2 != B.end()) {
		if(liter2 == B.begin()) {
			cout << *liter4;
		} else {
			cout <<","<< *liter2;
		}
		++liter2;
	}
	return 0;
}

If I run it , in the place where I used the iterators second time the code doesnt print what its supposed to print, it prints empty lines, why is that happening?
Last edited on
You never reset your iterators to the beginning of the container.

After pushing and popping, you want something like this prior to your while loops:
1
2
liter1 = A.begin();
liter2 = B.begin();
Topic archived. No new replies allowed.