c++ - 为什么可以取消引用 C++ 迭代器,尽管它不是指针?

标签 c++ iterator dereference

我正在阅读 C++ Primer 5th,遇到如下代码:

    string s("some string");
    if (s.begin() != s.end())
    {
      auto it = s.begin();   
      *it = toupper(*it);
    }

从迭代器接收一个值到字符串s中的第一个字符;然后通过 toupper() 将其更改为大写。 it 是如何取消引用的?不应该只是一个char类型的变量而不是指针吗?

最佳答案

是一个 iterator :

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:

由于迭代器是一个行为类似于指针的智能对象(最初指向字符串的开头 - 这是一个 container ),并迭代该容器, 可以取消引用,如您的代码示例所示。因此,通常 可以用作指针。

其中,在您的情况下,指针在字符串中的当前位置被分配给它在该位置的大写等价物:

*it = toupper(*it);

关于c++ - 为什么可以取消引用 C++ 迭代器,尽管它不是指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15961360/

相关文章:

c++ - nm 命令中的 "symbol value"是什么意思?

c++ - 取消引用字符串迭代器产生 int

c - 为什么一元 * 运算符没有约束 "the operand shall not be a pointer to void"?

Java - 按降序遍历 Mapset,返回所需的输出

perl - 哈希的未知哈希

c++ - Visual Studio 2015 中的 "non-standard syntax; use ' 和 ' to create a pointer to member"错误

c++ - Qt例子: no mutex lock when reading,为什么?

c++ - 如何将文本添加到 qtablewidget 的单元格

c++ - 分层数据的另一个迭代器中是否应该有一个迭代器?

PHP 生成器返回类型