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.
这篇关于迭代器 = 指针?或者它是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:迭代器 = 指针?或者它是什么?
基础教程推荐
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01