为什么C ++迭代器不是指针,却可以取消引用? [英] Why can a C++ iterator be dereferenced although it isn't a pointer?
问题描述
我正在阅读C ++ Primer 5th,遇到的代码看起来像这样:
I'm reading C++ Primer 5th, and I encounter code that looks like this:
string s("some string");
if (s.begin() != s.end())
{
auto it = s.begin();
*it = toupper(*it);
}
it
从迭代器接收到字符串s
中第一个字符的值;然后用toupper()
将其更改为大写. it
如何可以取消引用?不应该只是一个char类型的变量而不是一个指针吗?
it
receives a value from the iterator to the first character in string s
; it is then changed to upper case by toupper()
. How is it that it
can be dereferenced? Shouldn't it just be a char type variable and not a pointer?
推荐答案
it
是迭代器:
在C ++中,迭代器是指向对象中某个元素的任何对象. 一定范围的元素(例如数组或容器)具有 使用一组运算符迭代该范围的元素 (至少是递增(++)和取消引用(*)运算符.)
In C++, an iterator is any object that, pointing to some element in a range of elements (such as an array or a container), has the ability to iterate through the elements of that range using a set of operators (at least, the increment (++) and dereference (*) operators).
最明显的迭代器形式是指针:指针可以指向 数组中的元素,并可以使用增量迭代它们 运算子(++).但是存在其他形式的迭代器.例如,每个 容器类型(例如向量)具有特定的迭代器类型 旨在以有效的方式遍历其元素.
The most obvious form of iterator is a pointer: A pointer can point to elements in an array, and can iterate through them using the increment operator (++). But other forms of iterators exist. For example, each container type (such as a vector) has a specific iterator type designed to iterate through its elements in an efficient way.
请注意,尽管指针是迭代器的一种形式,但并非所有迭代器 具有与指针相同的功能;区分 迭代器对特定算法的要求,五个 存在不同的迭代器类别:
Notice that while a pointer is a form of iterator, not all iterators have the same functionality a pointer has; To distinguish between the requirements an iterator shall have for a specific algorithm, five different iterator categories exist:
由于迭代器是行为类似于指针的智能对象(最初指向字符串的开头-这是
Since an iterator is a smart object that behaves like a pointer (initially pointing to the beginning of the string - which is a container), and iterates over that container, it
can be dereferenced, as shown in your code sample. Hence, in general it
can be used as pointer.
在您的情况下,将指针在字符串中的当前位置分配为与该位置的 相同的大写字母:
Which, in your case, the current position of the pointer in the string is being assigned to the uppercase equivalent of what it was at that position:
*it = toupper(*it);
这篇关于为什么C ++迭代器不是指针,却可以取消引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!