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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With