What Is an Iterator?
Iterators (also sometimes called cursors) are software design patterns for programming. An interface that can be accessed on a container (such as a linked list or array). Designers do not need to care about the contents of the container.
Iterator
- Iterators, sometimes called cursors, are programmed
- An iterator is an object that can be used to traverse some or all of the elements in a standard template library container. Each iterator object represents a certain address in the container. Iterator modified general
#include <iostream> using namespace std; class _iterator { private: char * p; public: _iterator (char * str): p (str) () char * & operator ++ () { p + = 1; // same price as p ++; return p; } }; int main () { char * p = "This is C ++ program"; _iterator it (p); Before cout << "++:" << p << endl; char * p1 = ++ it; // Add a char length to the address, and then give pointer p1 After cout << "++:" << p1 << endl; return 0; }
- Iterator mode. Iterator can return such an Iterator object for any implementation class in the collection class. Just like the loop, the advantage is that it can be applied to any class, and in fact java has optimized it, which is faster than using index access directly (this cannot be verified, others say so). However, one thing is very good, it is really easy to use, plus generics is even better. For example, such an example ArrayList <String> arr = new ArrayList <String> (); Iterator it = arr.iterator (); While iterating, you can do this while (it .hasNext ()) {// Do some processing, such as System .out.print (it.next);} Cooperating with generics, one advantage is that it does not need type conversion for it.next (). In the past, it was Object, and I had to transfer it myself. I feel that Iterator and generics are a perfect match.