[TODO]Iterator, foreach, generics and callback in C# and Python

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

C++ version

Python version

C# version

    原文作者:dukeyunz
    原文地址: https://segmentfault.com/a/1190000003795962
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞