Reputation: 99
Do iterators have begin() and end() defined as member functions? I thought that containers had begin() and end() defined, and iterators had a limited amount of operations available, such as comparison, incrementing, and dereferencing. In the code sample below, it seems like he's using begin() and end() on iterators, and I'm not sure how this would work. Is this a mistake, or am I missing something?
The images below are from Bjarne Stroustrup's "Programming: Principles and Practices", pages 737 and 738 from Chapter 20. The only important parts are the definitions of ln and pos in the Text_iterator class, and the usage of (*ln).end(). I marked (*ln).end() with a 2. For context, he's defining an iterator for the class Document, which is an in-memory representation of a text file.
Thank you.
A related question, does anyone know how to contact Bjarne? I want to ask him this question, but I don't know his email. From his FAQ, it seems like he welcomes emails, but it doesn't say it anywhere.
Upvotes: 1
Views: 124
Reputation: 33932
No. The typical iterator has no begin
or end
method. begin
and end
are not being invoked on the iterator, they are being invoked on the object referenced by the iterator. *ln
dereferences the iterator and provides the object referenced by the iterator, a Line
in this case. (*ln).end()
means "Get me the Line
object at ln
and invoke the end
method on it." Whatever Line
is must have begin
and end
methods or the compiler will catch the error.
Walking through the logic, we get
++pos; // advance iterator one character in the current Line
if (pos==(*ln).end()) { // if this character is the the `Line`'s end iterator
// we need a new line
{
++ln; // advance to the next line
pos = (*ln).begin(); // referenced character is first character in next line
}
return *this;
This allows the user to iterate through a document character by character without realizing they are actually traversing lines, allowing the writer to use the code they already have for traversing lines in the document and characters in the line. Practically no new code is written for what otherwise could be a complicated task.
Upvotes: 3