Why can a C++ iterator be dereferenced although it isn't a pointer?

牧云@^-^@ 提交于 2020-01-05 08:02:32

问题


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 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?


回答1:


it is an 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:

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);



回答2:


The iterator type (and this is something that is obscured by using the magical auto keyword) is a complicated thing, not a primitive object.

When you ask for*it, you are given a reference to the char at that position. Hence you can modify it.




回答3:


    Shouldn't it just be a char type variable and not a pointer?

"it" is an iterator(pointer like object) and not a pointer. There are definite benefits of choosing iterators over pointers. One striking benefit is to separate algorithm from Containers. Thus have generic algorithms(constrained only by the type of iterators) and thus decouple Containers from algorithms.

Pls have a look at STL iterators - purpose.



来源:https://stackoverflow.com/questions/15961360/why-can-a-c-iterator-be-dereferenced-although-it-isnt-a-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!