C + + iterators (iterator)

Source: Internet
Author: User
Tags types of functions

1. an iterator (iterator) is a data type that examines the elements within a container and iterates through the elements.
(1) Each container type defines its own iterator type, such as vector:
Vector<int>::iterator ITER; This statement defines a variable named ITER whose data type is the iterator type defined by vector<int>.
(2) Use an iterator to read every element in the vector:
Vector<int> Ivec (10,1);
For (Vector<int>::iterator Iter=ivec.begin (); Iter!=ivec.end (); ++iter)
{
*iter=2; Use * To access the element that the iterator points to
}
Const_iterator:
Only the elements in the container can be read, not modified.
For (Vector<int>::const_iterator Citer=ivec.begin (); Citer!=ivec.end (); citer++)
{
cout<<*citer;
*citer=3; Error
}
The difference between Vector<int>::const_iterator and const Vector<int>::iterator
Const Vector<int>::iterator Newiter=ivec.begin ();
*newiter=11; You can modify the elements that point to the container
newiter++; Iterators themselves cannot be modified
(3) Arithmetic operation of iterator:
Iterator you can assign the Iter+n,iter-n to a new Iteraor object in addition to the + +,--operation. You can also use one iterator minus the other iterator.
Const Vector<int>::iterator Newiter=ivec.begin ();
Vector<int>::iterator Newiter2=ivec.end ();
cout<< "\ n" <<newiter2-newiter;
A typical STL program that uses vectors:

 #include <vector> #include <iostream> using namespace Std;int main () {vector<int> Ivec;ivec.push_ Back (1); Ivec.push_back (2), Ivec.push_back (3); Ivec.push_back (4); for (Vector<int>::iterator iter = Ivec.begin () ; 1. Iter! = Ivec.end (); ++iter) cout << *iter << Endl;} 

2. Iterator (iterator) mode
I. Overview
The Iterator (iterator) mode, also known as the cursor pattern, provides a way to sequentially access individual elements of an aggregated object without exposing the object's internal representation. Or it might be easier to understand: the iterator pattern is a pattern applied to the aggregation object, which allows us to access the individual elements of the aggregation object in a certain order (the method provided by iterator) without knowing the inner representation of the object.
Because of the above features of the iterator mode: coupling with the aggregation object, to a certain extent, limited its extensive use, generally only for the underlying aggregation support classes, such as the STL list, vector, stack and other container classes and ostream_iterator extension iterator.
According to the classification in STL, iterator includes:
Input Iterator: The element can only be iterated forward, and the element referenced by that class iterator is not allowed to be modified.
Output Iterator: This type of iterator is very similar to input Iterator, and can only step forward iteratively, except that the class iterator has only write power over the element.
Forward Iterator: This type of iterator can read and write in a correct interval, has all the attributes of input Iterator, and some features of output Iterator, as well as the ability to step forward iterative elements.
bidirectional Iterator: This type of iterator provides the ability to iterate over elements in a single step, based on the forward Iterator.
Random Access Iterator: This type of iterator can do the work of all the above iterators, and its own unique feature is that it can perform arithmetic calculations like pointers, rather than just stepping forward or backward.
The dependencies of these five types of iterators, as shown, where the arrow a→b indicates that A is a hardening type of B, also shows that if an algorithm requires B, then a can also be applied to it.

Input Output
\ /
Forward
|
Bidirectional
|
Random Access
Figure 1, the relationship between the five iterators
Vectors and deque provide the iterators provided by Randomaccessiterator,list is ForwardIterator, which is provided by Bidirectionaliterator,set and map, The operations for iterator iterators in STL are as follows:
DescriptionEach iterator can perform operations that include the previous iterator in the table.
Iterator Operation Instructions
(1) All iterators
p++ Post-built self-increment iterator
++p forward self-increment iterator
(2) Input iterator
*p Complex reference iterator, as Rvalue
P=p1 assigning an iterator to another iterator
P==P1 comparison of equality of iterators
P!=p1 comparison of the inequality of iterators
(3) Output iterator
*p Complex reference iterator, as Lvalue
P=p1 assigning an iterator to another iterator
(4) Forward iterator
Provides all the functions of an input-output iterator
(5) Bidirectional iterator
--p pre-built-in self-reducing iterators
p--post-offset self-reducing iterator
(6) Random iterators
P+=i increments the iterator I bit
P-=i decrements the iterator i-bit
P+i iterator after P-bit plus I-bit
P-i iterator after P-bit minus I bit
P[i] Returns the element reference of the P-bit element deviating from the I bit
P&LT;P1 returns True if the position of the iterator P is before P1, otherwise false
Returns true if the position of the P&LT;=P1 P is in front of the P1 or in the same position, otherwise false
P&GT;P1 returns True if the position of the iterator P is P1, otherwise false
P&GT;=P1 P's position returns true at the back of the P1 or in the same position, otherwise false
Only sequential containers and associative containers support iterator traversal, and the categories of iterators supported by each container are as follows:
Iterator categories supported by container-supported iterator category containers for containers
Vector random Access deque random access list bidirectional
Set bidirectional multiset bidirectional map double To
Multimap bidirectional stack does not support queue not supported
Priority_queue not supported
Second, the structure
The structure of the iterator pattern is as follows:


Figure 2, iterator pattern diagram schematic
Third, the application
The iterator model has three important functions:
1) It supports traversing a single aggregation in a different way. Complex aggregations can be traversed in many ways, such as a binary tree traversal, using a pre-order, a middle-order, or a sequential traversal. The iterator pattern makes it easy to change the traversal algorithm: just replace the original instance with an instance of a different iterator, and you can define the subclass of the iterator to support the new traversal, or you can add some logic to the traversal, such as conditional traversal.
2) iterators simplify the interface for aggregation. With an iterator traversal interface, the aggregation itself no longer requires a similar traversal interface, which simplifies the aggregation interface.
3) on the same aggregation can have multiple traversal each iterator to maintain its own traversal state, so you can do multiple traversal at the same time.
4) In addition, the iterator mode provides a unified interface for traversing different aggregation structures (which need to have the same base class), that is, support for polymorphic iterations.
In short, the iterator pattern is also an application of the delegate principle, which encapsulates the ability to traverse a collection into a separate iterator, simplifying the interface of the collection and making it easier to modify and increase the traversal. From this point of view, the model and bridge mode, strategy model has a certain similarity, but the iterator model discussed the problem and set is closely related, resulting in iterator in the realization of a certain particularity, will be discussed in the Example section.
Iv. Advantages and Disadvantages
As previously mentioned, it is closely related to the collection, which limits the widespread use of the iterator model, and personally, I do not agree with the idea of iterator as a model, but it does conform to the nature of the pattern "solutions to specific problems" that I have to admit is a pattern. In the general support class of the underlying collection, we often do not want to "avoid light on the weight" of the collection design into a collection + Iterator form, but the traversal of the function directly to the collection to avoid the "excessive design" of the criticism, but, If our collection class does need to support multiple traversal methods (this point still doesn't necessarily need to consider the iterator pattern, it is often more convenient to go directly to the collection), or the iterator mode is worth considering in order to be consistent with other mechanisms provided or used by the system, such as the STL algorithm.
V. Examples
There are two ways to implement the iterator pattern: an inline class or a friend class. Typically iterative classes need access to the internal data structures in the collection class, and for this reason, it is possible to set the iteration class to friend class in the collection class, but this is not conducive to adding a new iteration class, because the collection class needs to be modified and a friend Class statement added. It is also possible to define protected types of functions that access the internal data of the collection class in an abstract iterative class, so that the iterative subclasses can access the collection class data, which is easier to add new iterations, but there are also obvious drawbacks: These functions can only be used for specific aggregation classes, and Inevitably makes the code more complex.
STL's List::iterator, Deque::iterator, Rbtree::iterator and so on are all the forms of the external iterator class, although the iterator of the STL collection classes are scattered among the various collection classes, But because each iterator class has the same base class, maintains the same external interface (including some traits and tags, etc., interested people please carefully read reference 1, 2), so that they still look like a whole, but also make the application algorithm become possible. If we want to extend the iterator of STL, we need to pay attention to this point, otherwise, our extended iterator will probably not be applied to each algorithm.
The following is an example of a traversal of a binary tree, in order to facilitate the iterator of multiple traversal modes, and to facilitate the extension of traversal, which also uses the strategy pattern (see note 21):
(Note: 1, although the following example is the most time spent in all the examples in this series, I have to admit that it is very imperfect, interested friends, can consider reference to the following reference material to complement it, or to make valuable suggestions for improvement. 2, I would like to consider encapsulating it into a form consistent with the STL style, so that we traverse the binary tree must be carried out through the iterator, but because the binary tree in the structure of the more linear storage structure complex, so that access must be through the iterator, But this inevitably makes Binarytree's visit extremely troublesome and needs serious consideration in specific applications. 3, the following only provides the implementation of inorder< > Traversal iterator. )

C + + iterators (iterator)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.