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.
这篇关于迭代器 = 指针?或者它是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:迭代器 = 指针?或者它是什么?


基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01