迭代器 = 指针?或者它是什么?

Iterator = pointer? Or what is it?(迭代器 = 指针?或者它是什么?)

本文介绍了迭代器 = 指针?或者它是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Is an iterator in C++ a pointer? The reason I ask is that it seems like nobody completely understands what an iterator is. It's just a "thing" or a "value" they say. But an iterator simply points to the element, to its position. When we dereference it, it's like looking at what an iterator points to.

Is it a correct analogy?

解决方案

The short answer is:

  • Pointer is a kind of iterator.
  • Pointer can be therefore used as an iterator.
  • Pointer has properties other than iterator.

History

Historically, we have C pointer, and it is adapted into C++ when C++ is invented. Pointer represents a location in memory, therefore can be used as a location in an array.

Later, in 1990s, an idea called "iterator concept" is introduced to C++. The "iterator concept" is related to a library called STL (which is later absorbed into the Standard Library) and a paradigm called "generic programming". The iterator concept is inspired from C pointer to represent a location in containers like vector, deque and others, just like how C pointer represent location in array. The iterator concept is carefully engineered to be compatible with C pointer, hence we can nowadays say C pointer models iterator concept.

Iterator concept

A simplified way to understand iterator concept is that, if a data type suppports a list of operations and behaviours, such that it represent a location in a container, and enable some kind of access to the element, it can be called an iterator.

With carefull design of iterator concept, C pointer fulfill that list. Pointer is therefore a kind of iterator.

Iterator concept being just a set of requirement on types, means that you can create your own iterator through C++ power of data abstraction.

Other properties of pointer

Pointer exhibits other properties, and they are not related to iterator concept.

A significant use of pointer is to express reference semantics, i.e. to refer to an object in a remote memory location. This usage of pointer is later considered unsafe, and causes the invention of "smart pointer". By comparing smart pointers and iterators, we can find that they are totally unrelated concepts.

Another use of pointer is to refer to a raw memory location. This is completely unsafe for application programming, but is a essential tool for microcontroller programming to manipulate hardware.

这篇关于迭代器 = 指针?或者它是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:迭代器 = 指针?或者它是什么?

基础教程推荐