The difference between iterator and pointer

The iterator encapsulates the method of "traversing the container". The traversal implementation of different containers is different. For example, an array can be traversed only with a given offset, and a linked list requires some "complex" jump operations. It can be seen that the iterator unifies the traversal operation through encapsulation and reduces the programming effort. Complexity (iterator does it for you).

For a simple example, customize the function of finding the maximum value findMax. For different containers, you must define an array version and a linked list version of overloaded functions, and continue to define different containers. Not only do you need to bother to think about the details of the structure traversal operation, There are many forms of overloading. The iterator abstracts the operations of various containers, concealing the operation details, and the user only needs to complete the task according to the abstracted operation.

Specifically, the differences between them are:
(1) Iterators are class templates that mimic pointers . Such pointer operator, ->, *, ++ --encapsulates the pointer is a "can traverse all or part of the container element STL (Standard Template Library)" object, essentially encapsulates the original pointer, a pointer to enhance the concept (Lift) , Provides a more advanced behavior than pointers: according to different types of data structures to achieve different ++,-and other operations;
(2) in the design mode there is a mode called iterator mode. This mode provides no need to expose the internal representation of a certain container to complete the operation of traversing the container. Iterator parameters are widely used in STL algorithms. Through iterators, containers and algorithms can be organically glued together, and we basically do not need to consider the underlying implementation to complete some general algorithms. You need to pay attention to the failure problem after using the iterator algorithm .
(3) Pointers can point to functions, and iterators can only point to containers.

[1] https://blog.csdn.net/qq_42565910/article/details/89068025
[2] https://www.zhihu.com/question/54047747

Guess you like

Origin blog.csdn.net/weixin_39258979/article/details/114001426