我正在阅读 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/