A brief analysis of the difference between iterator and pointer

  • 2020-04-02 01:46:45
  • OfStack

1. Both pointer and iterator support + and - operations with integers, and their meanings are to move n positions forward or backward from the current position

2. Both pointer and iterator support subtraction operation. The distance between two Pointers is obtained by pointer - pointer, and the distance between two iterators is obtained by iterator - iterator

3. The element to which it refers can be modified by pointer or iterator

From the above point of view, the two are really similar, but they also have a few different places below

1. The cout operator can directly output the value of the pointer, but it will report an error when operating on the iterator. By reading the error message and the header file, we can know that the iterator returns an object reference rather than the value of the object, so cout can only output the value of the iterator after using the value of * instead of directly output itself.

2. Pointers can point to functions but iterators can't. Iterators can only point to containers

This shows that iterators and Pointers are completely different concepts. A pointer is a special variable that holds the address of another variable, and an iterator is just an STL interface designed with the pointer in mind.

I have seen a statement on the Internet that iterators are generalized Pointers, and Pointers satisfy all iterator requirements. The iterator is the interface to the STL algorithm, and the pointer is the iterator, so the STL algorithm can use the pointer to operate on non-stl containers based on the pointer.

The author thinks the above statement also has some truth, but in the end is not correct left to see their own judgment. One thing I'd like you to note is that you should never confuse Pointers and iterators. Maybe some compilers use Pointers to implement iterators so that some people mistake Pointers and iterators for concepts.


Related articles: