STL iterator

作者:jicanmeng

时间:2017年06月21日


iterator的两个例子:

遍历vector:

#include <iostream>
#include <vector>

int main()
{
    using namespace std;

    vector<int> vect;
    for (int nCount=0; nCount < 6; nCount++)
        vect.push_back(10 - nCount); // insert at end of array

    vector<int>::const_iterator it; // declare a read-only iterator
    it = vect.begin(); 			// assign it to the start of the vector
    while (it != vect.end()) {	// while it hasn't reach the end
        cout << *it << " "; // print the value of the element it points to
        ++it; // and iterate to the next element
    }

    cout << endl;
}

运行结果和上一篇文章的结果一样:

[jicanmeng@andy tmp]$ ./a.out
                10 9 8 7 6 5
			[jicanmeng@andy tmp]$

遍历list:

#include <iostream>
#include <list>

int main()
{
    using namespace std;

    list<int> li;
    for (int nCount = 0; nCount < 6; nCount++)
        li.push_back(nCount);

    list<int>::const_iterator it; // declare an iterator
    it = li.begin(); 			// assign it to the start of the vector
    while (it != li.end()) {	// while it hasn't reach the end
        cout << *it << " "; // print the value of the element it points to
        ++it; // and iterate to the next element
    }

    cout << endl;
}

以下是运行结果:

[jicanmeng@andy tmp]$ ./a.out
                0 1 2 3 4 5
			[jicanmeng@andy tmp]$

参考资料

  1. <<C++实用教程>> 电子工业出版社 郑阿奇 主编 丁有和 编著 P280
  2. The C++ Tutorial:
    http://www.learncpp.com/cpp-tutorial/16-1-the-standard-template-library-stl/
  3. misc:
    http://www.cnblogs.com/shiyangxt/archive/2008/09/11/1289493.html