It seems like a huge topic, so just divide it into small pieces and conquer them piece by piece, I have drawn a map for this article to guide me finish it instead of being scared by it.
Iterator
Concept of iterator is here in #Wikipedia: Iterator , so I think iterator is just like pointer in C or cursor in database.
why use iterator
Iterator is just an abstract concept and can be implemented in many different ways. But first of all, we should figure out why we need iterator and why it is important for us.
First, just think about a simple for
loop in C++:
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 3; i++)
cout << i << " ";
cout << endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int a[] = { 1, 2, 3 };
for (int i = 0; i < 3; i++)
cout << a[i] << " ";
cout << endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int a[] = { 1, 2, 3 };
for (int i = 0; i < 3; i++)
cout << *(a+i) << " ";
cout << endl;
system("pause");
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
for (vector<int>::iterator i = a.begin();
i != a.end();
i++)
cout << *i << " ";
cout << endl;
system("pause");
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
for (auto i : a)
cout << i << " ";
cout << endl;
system("pause");
return 0;
}
In C++, if we implement a container of our own, and we want to use for loop or while loop to traverse it like basic data type, we can use iterator by implement
So first let's analysis this example in
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。