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